Mendapatkan nama host instance Compute Engine

Contoh ini mengambil nama host instance Compute Engine tertentu.

Contoh kode

Go

Sebelum mencoba contoh ini, ikuti petunjuk penyiapan Go di panduan memulai Compute Engine menggunakan library klien. Untuk informasi selengkapnya, lihat dokumentasi referensi API Go Compute Engine.

Untuk melakukan autentikasi ke Compute Engine, siapkan Kredensial Default Aplikasi. Untuk mengetahui informasi selengkapnya, baca Menyiapkan autentikasi untuk lingkungan pengembangan lokal.

import (
	"context"
	"fmt"
	"io"

	compute "cloud.google.com/go/compute/apiv1"
	computepb "cloud.google.com/go/compute/apiv1/computepb"
)

// getInstanceHostname prints the hostname of the Google Cloud VM instance.
func getInstanceHostname(w io.Writer, projectID, zone, instanceName string) error {
	// projectID := "your_project_id"
	// zone := "europe-central2-b"
	// instanceName := "your_instance_name"

	ctx := context.Background()
	instancesClient, err := compute.NewInstancesRESTClient(ctx)
	if err != nil {
		return fmt.Errorf("NewInstancesRESTClient: %w", err)
	}
	defer instancesClient.Close()

	req := &computepb.GetInstanceRequest{
		Project:  projectID,
		Zone:     zone,
		Instance: instanceName,
	}

	instance, err := instancesClient.Get(ctx, req)
	if err != nil {
		return fmt.Errorf("unable to get instance: %w", err)
	}

	// If a custom hostname is not set, the output for instance.GetHostname() will be ""
	fmt.Fprintf(w, "Instance %v has hostname: %v", instanceName, instance.GetHostname())

	return nil
}

Java

Sebelum mencoba contoh ini, ikuti petunjuk penyiapan Java di panduan memulai Compute Engine menggunakan library klien. Untuk informasi selengkapnya, lihat dokumentasi referensi API Java Compute Engine.

Untuk melakukan autentikasi ke Compute Engine, siapkan Kredensial Default Aplikasi. Untuk mengetahui informasi selengkapnya, baca Menyiapkan autentikasi untuk lingkungan pengembangan lokal.


import com.google.cloud.compute.v1.Instance;
import com.google.cloud.compute.v1.InstancesClient;
import java.io.IOException;

public class GetInstanceHostname {

  public static void main(String[] args) throws IOException {
    // TODO(developer): Replace these variables before running the sample.
    String project = "your-project-id";
    String zone = "zone-name"; // eg: "us-central1-a"
    String instanceName = "instance-name"; // Name of the VM instance to retrieve.

    getInstanceHostname(project, zone, instanceName);
  }

  // Retrieves the hostname of the Google Cloud VM instance.
  public static void getInstanceHostname(String projectId, String zone, String instanceName)
      throws IOException {
    try (InstancesClient instancesClient = InstancesClient.create()) {

      Instance instance = instancesClient.get(projectId, zone, instanceName);

      if (instance.hasHostname()) {
        // If a custom hostname is not set, the output for instance.getHostname() will be undefined.
        System.out.printf("Custom Hostname for the instance %s is: %s", instanceName,
            instance.getHostname());
      }
    }
  }

}

Node.js

Sebelum mencoba contoh ini, ikuti petunjuk penyiapan Node.js di panduan memulai Compute Engine menggunakan library klien. Untuk informasi selengkapnya, lihat dokumentasi referensi API Node.js Compute Engine.

Untuk melakukan autentikasi ke Compute Engine, siapkan Kredensial Default Aplikasi. Untuk mengetahui informasi selengkapnya, baca Menyiapkan autentikasi untuk lingkungan pengembangan lokal.

/**
 * TODO(developer): Uncomment and replace these variables before running the sample.
 */
// const projectId = 'YOUR_PROJECT_ID';
// const zone = 'europe-central2-b'
// const instanceName = 'YOUR_INSTANCE_NAME'

const compute = require('@google-cloud/compute');

async function getInstanceHostname() {
  const instancesClient = new compute.InstancesClient();

  const [instance] = await instancesClient.get({
    project: projectId,
    zone,
    instance: instanceName,
  });
  // If a custom hostname is not set, the output for instance.hostname will be undefined
  console.log(`Instance ${instanceName} has hostname: ${instance.hostname}`);
}

getInstanceHostname();

Python

Sebelum mencoba contoh ini, ikuti petunjuk penyiapan Python di panduan memulai Compute Engine menggunakan library klien. Untuk informasi selengkapnya, lihat dokumentasi referensi API Python Compute Engine.

Untuk melakukan autentikasi ke Compute Engine, siapkan Kredensial Default Aplikasi. Untuk mengetahui informasi selengkapnya, baca Menyiapkan autentikasi untuk lingkungan pengembangan lokal.

from google.cloud import compute_v1

def get_hostname(project_id: str, zone: str, instance_name: str) -> str:
    """
    Retrieve the hostname of given instance.

    Args:
        project_id: project ID or project number of the Cloud project you want to use.
        zone: name of the zone you want to use. For example: "us-west3-b"
        instance_name: name of the virtual machine to check.

    Returns:
        The hostname of an instance.
    """
    instance_client = compute_v1.InstancesClient()
    instance = instance_client.get(
        project=project_id, zone=zone, instance=instance_name
    )
    return instance.hostname

Langkah selanjutnya

Untuk menelusuri dan memfilter contoh kode untuk produk Google Cloud lainnya, lihat browser contoh Google Cloud.