Hostname einer Compute Engine-Instanz abrufen

In diesem Beispiel wird der Hostname einer bestimmten Compute Engine-Instanz abgerufen.

Codebeispiel

Go

Bevor Sie dieses Beispiel anwenden, folgen Sie den Schritten zur Einrichtung von Go in der Compute Engine-Kurzanleitung zur Verwendung von Clientbibliotheken. Weitere Informationen finden Sie in der Referenzdokumentation zur Compute Engine Go API.

Richten Sie die Standardanmeldedaten für Anwendungen ein, um sich bei Compute Engine zu authentifizieren. Weitere Informationen finden Sie unter Authentifizierung für eine lokale Entwicklungsumgebung einrichten.

import (
	"context"
	"fmt"
	"io"

	compute "cloud.google.com/go/compute/apiv1"
	computepb "google.golang.org/genproto/googleapis/cloud/compute/v1"
)

// 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

Bevor Sie dieses Beispiel anwenden, folgen Sie den Schritten zur Einrichtung von Java in der Compute Engine-Kurzanleitung zur Verwendung von Clientbibliotheken. Weitere Informationen finden Sie in der Referenzdokumentation zur Compute Engine Java API.

Richten Sie die Standardanmeldedaten für Anwendungen ein, um sich bei Compute Engine zu authentifizieren. Weitere Informationen finden Sie unter Authentifizierung für eine lokale Entwicklungsumgebung einrichten.


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

Bevor Sie dieses Beispiel anwenden, folgen Sie den Schritten zur Einrichtung von Node.js in der Compute Engine-Kurzanleitung zur Verwendung von Clientbibliotheken. Weitere Informationen finden Sie in der Referenzdokumentation zur Compute Engine Node.js API.

Richten Sie die Standardanmeldedaten für Anwendungen ein, um sich bei Compute Engine zu authentifizieren. Weitere Informationen finden Sie unter Authentifizierung für eine lokale Entwicklungsumgebung einrichten.

/**
 * 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

Bevor Sie dieses Beispiel anwenden, folgen Sie den Schritten zur Einrichtung von Python in der Compute Engine-Kurzanleitung zur Verwendung von Clientbibliotheken. Weitere Informationen finden Sie in der Referenzdokumentation zur Compute Engine Python API.

Richten Sie die Standardanmeldedaten für Anwendungen ein, um sich bei Compute Engine zu authentifizieren. Weitere Informationen finden Sie unter Authentifizierung für eine lokale Entwicklungsumgebung einrichten.

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

Nächste Schritte

Informationen zum Suchen und Filtern von Codebeispielen für andere Google Cloud-Produkte finden Sie im Google Cloud-Beispielbrowser.