Obtén una lista de las VM


Para ver un resumen de las VM que se ejecutan en tu proyecto, obtén una lista de las VM. En este documento, se muestra cómo obtener una lista de las VM en todas las zonas o en zonas específicas.

Antes de comenzar

  • Configura la autenticación si aún no lo hiciste. La autenticación es el proceso mediante el cual se verifica tu identidad para acceder a los servicios y las API de Google Cloud. Para ejecutar un código o muestras desde un entorno de desarrollo local, puedes autenticarte en Compute Engine de la siguiente manera.

    Selecciona la pestaña para saber cómo planeas usar las muestras en esta página:

    Consola

    Cuando usas la consola de Google Cloud para acceder a los servicios y las APIs de Google Cloud, no necesitas configurar la autenticación.

    gcloud

    1. Instala Google Cloud CLI y, luego, inicializa la ejecución del siguiente comando:

      gcloud init
    2. Configura una región y una zona predeterminadas.

    Go

    Para usar las muestras de Go de esta página desde un entorno de desarrollo local, instala e inicializa la CLI de gcloud y, luego, configura las credenciales predeterminadas de la aplicación con tus credenciales de usuario.

    1. Instala Google Cloud CLI.
    2. Para inicializar la CLI de gcloud, ejecuta el siguiente comando:

      gcloud init
    3. Crea credenciales de autenticación locales para tu Cuenta de Google:

      gcloud auth application-default login

    Para obtener más información, consulta Configura la autenticación para un entorno de desarrollo local.

    Java

    Para usar las muestras de Java de esta página desde un entorno de desarrollo local, instala e inicializa la CLI de gcloud y, luego, configura las credenciales predeterminadas de la aplicación con tus credenciales de usuario.

    1. Instala Google Cloud CLI.
    2. Para inicializar la CLI de gcloud, ejecuta el siguiente comando:

      gcloud init
    3. Crea credenciales de autenticación locales para tu Cuenta de Google:

      gcloud auth application-default login

    Para obtener más información, consulta Configura la autenticación para un entorno de desarrollo local.

    Node.js

    Para usar las muestras de Node.js de esta página desde un entorno de desarrollo local, instala e inicializa la CLI de gcloud y, luego, configura las credenciales predeterminadas de la aplicación con tus credenciales de usuario.

    1. Instala Google Cloud CLI.
    2. Para inicializar la CLI de gcloud, ejecuta el siguiente comando:

      gcloud init
    3. Crea credenciales de autenticación locales para tu Cuenta de Google:

      gcloud auth application-default login

    Para obtener más información, consulta Configura la autenticación para un entorno de desarrollo local.

    Python

    Para usar las muestras de Python de esta página desde un entorno de desarrollo local, instala e inicializa la CLI de gcloud y, luego, configura las credenciales predeterminadas de la aplicación con tus credenciales de usuario.

    1. Instala Google Cloud CLI.
    2. Para inicializar la CLI de gcloud, ejecuta el siguiente comando:

      gcloud init
    3. Crea credenciales de autenticación locales para tu Cuenta de Google:

      gcloud auth application-default login

    Para obtener más información, consulta Configura la autenticación para un entorno de desarrollo local.

    REST

    Para usar las muestras de la API de REST en esta página en un entorno de desarrollo local, debes usar las credenciales que proporcionas a la CLI de gcloud.

      Instala Google Cloud CLI y, luego, inicializa la ejecución del siguiente comando:

      gcloud init

Obtén una lista de las VM

Console

En la consola de Google Cloud, ve a la página Instancias de VM.

Ir a Instancias de VM

gcloud

Obtén una lista agregada de todas las VM en todas las zonas de un proyecto con el comando gcloud compute instances list:

gcloud compute instances list

Para limitar la lista de las VM a una zona específica, usa el comando anterior con la marca --zones.

Go

En el siguiente ejemplo, puedes obtener una lista de instancias en todas las zonas de tu proyecto:

Antes de probar esta muestra, sigue las instrucciones de configuración de Go en la Guía de inicio rápido de Compute Engine: Usa las bibliotecas cliente. Si quieres obtener más información, consulta la documentación de referencia de la API de Go de Compute Engine.

Para autenticarte en Compute Engine, configura las credenciales predeterminadas de la aplicación. Si deseas obtener más información, consulta Configura la autenticación para un entorno de desarrollo local.

import (
	"context"
	"fmt"
	"io"

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

// listAllInstances prints all instances present in a project, grouped by their zone.
func listAllInstances(w io.Writer, projectID string) error {
	// projectID := "your_project_id"
	ctx := context.Background()
	instancesClient, err := compute.NewInstancesRESTClient(ctx)
	if err != nil {
		return fmt.Errorf("NewInstancesRESTClient: %w", err)
	}
	defer instancesClient.Close()

	// Use the `MaxResults` parameter to limit the number of results that the API returns per response page.
	req := &computepb.AggregatedListInstancesRequest{
		Project:    projectID,
		MaxResults: proto.Uint32(3),
	}

	it := instancesClient.AggregatedList(ctx, req)
	fmt.Fprintf(w, "Instances found:\n")
	// Despite using the `MaxResults` parameter, you don't need to handle the pagination
	// yourself. The returned iterator object handles pagination
	// automatically, returning separated pages as you iterate over the results.
	for {
		pair, err := it.Next()
		if err == iterator.Done {
			break
		}
		if err != nil {
			return err
		}
		instances := pair.Value.Instances
		if len(instances) > 0 {
			fmt.Fprintf(w, "%s\n", pair.Key)
			for _, instance := range instances {
				fmt.Fprintf(w, "- %s %s\n", instance.GetName(), instance.GetMachineType())
			}
		}
	}
	return nil
}

También puedes obtener una lista de instancias en una zona específica:

// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package snippets

import (
	"context"
	"fmt"
	"io"

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

// listInstances prints a list of instances created in given project in given zone.
func listInstances(w io.Writer, projectID, zone string) error {
	// projectID := "your_project_id"
	// zone := "europe-central2-b"
	ctx := context.Background()
	instancesClient, err := compute.NewInstancesRESTClient(ctx)
	if err != nil {
		return fmt.Errorf("NewInstancesRESTClient: %w", err)
	}
	defer instancesClient.Close()

	req := &computepb.ListInstancesRequest{
		Project: projectID,
		Zone:    zone,
	}

	it := instancesClient.List(ctx, req)
	fmt.Fprintf(w, "Instances found in zone %s:\n", zone)
	for {
		instance, err := it.Next()
		if err == iterator.Done {
			break
		}
		if err != nil {
			return err
		}
		fmt.Fprintf(w, "- %s %s\n", instance.GetName(), instance.GetMachineType())
	}
	return nil
}

Java

En el siguiente ejemplo, puedes obtener una lista de instancias en todas las zonas de tu proyecto:

Antes de probar esta muestra, sigue las instrucciones de configuración de Java en la Guía de inicio rápido de Compute Engine: Usa las bibliotecas cliente. Si quieres obtener más información, consulta la documentación de referencia de la API de Java de Compute Engine.

Para autenticarte en Compute Engine, configura las credenciales predeterminadas de la aplicación. Si deseas obtener más información, consulta Configura la autenticación para un entorno de desarrollo local.


import com.google.cloud.compute.v1.AggregatedListInstancesRequest;
import com.google.cloud.compute.v1.Instance;
import com.google.cloud.compute.v1.InstancesClient;
import com.google.cloud.compute.v1.InstancesClient.AggregatedListPagedResponse;
import com.google.cloud.compute.v1.InstancesScopedList;
import java.io.IOException;
import java.util.Map;

public class ListAllInstances {

  public static void main(String[] args) throws IOException {
    // TODO(developer): Replace these variables before running the sample
    String project = "your-project-id";
    listAllInstances(project);
  }

  // List all instances in the specified project ID.
  public static AggregatedListPagedResponse listAllInstances(String project) throws IOException {
    // Initialize client that will be used to send requests. This client only needs to be created
    // once, and can be reused for multiple requests. After completing all of your requests, call
    // the `instancesClient.close()` method on the client to
    // safely clean up any remaining background resources.
    try (InstancesClient instancesClient = InstancesClient.create()) {

      // Use the `setMaxResults` parameter to limit the number of results
      // that the API returns per response page.
      AggregatedListInstancesRequest aggregatedListInstancesRequest = AggregatedListInstancesRequest
          .newBuilder()
          .setProject(project)
          .setMaxResults(5)
          .build();

      InstancesClient.AggregatedListPagedResponse response = instancesClient
          .aggregatedList(aggregatedListInstancesRequest);

      // Despite using the `setMaxResults` parameter, you don't need to handle the pagination
      // yourself. The returned `AggregatedListPager` object handles pagination
      // automatically, requesting next pages as you iterate over the results.
      for (Map.Entry<String, InstancesScopedList> zoneInstances : response.iterateAll()) {
        // Instances scoped by each zone
        String zone = zoneInstances.getKey();
        if (!zoneInstances.getValue().getInstancesList().isEmpty()) {
          // zoneInstances.getKey() returns the fully qualified address.
          // Hence, strip it to get the zone name only
          System.out.printf("Instances at %s: ", zone.substring(zone.lastIndexOf('/') + 1));
          for (Instance instance : zoneInstances.getValue().getInstancesList()) {
            System.out.println(instance.getName());
          }
        }
      }
      System.out.println("####### Listing all instances complete #######");
      return response;
    }
  }

}

También puedes obtener una lista de instancias en una zona específica:

/*
 * Copyright 2021 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package compute;

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

public class ListInstance {

  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";
    listInstances(project, zone);
  }

  // List all instances in the given zone in the specified project ID.
  public static void listInstances(String project, String zone) throws IOException {
    // Initialize client that will be used to send requests. This client only needs to be created
    // once, and can be reused for multiple requests. After completing all of your requests, call
    // the `instancesClient.close()` method on the client to
    // safely clean up any remaining background resources.
    try (InstancesClient instancesClient = InstancesClient.create()) {
      // Set the project and zone to retrieve instances present in the zone.
      System.out.printf("Listing instances from %s in %s:", project, zone);
      for (Instance zoneInstance : instancesClient.list(project, zone).iterateAll()) {
        System.out.println(zoneInstance.getName());
      }
      System.out.println("####### Listing instances complete #######");
    }
  }
}

Node.js

En el siguiente ejemplo, puedes obtener una lista de instancias en todas las zonas de tu proyecto:

Antes de probar esta muestra, sigue las instrucciones de configuración de Node.js en la Guía de inicio rápido de Compute Engine: Usa las bibliotecas cliente. Si quieres obtener más información, consulta la documentación de referencia de la API de Node.js de Compute Engine.

Para autenticarte en Compute Engine, configura las credenciales predeterminadas de la aplicación. Si deseas obtener más información, consulta Configura la autenticación para un entorno de desarrollo local.

/**
 * TODO(developer): Uncomment and replace these variables before running the sample.
 */
// const projectId = 'YOUR_PROJECT_ID';

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

// List all instances in the specified project.
async function listAllInstances() {
  const instancesClient = new compute.InstancesClient();

  //Use the `maxResults` parameter to limit the number of results that the API returns per response page.
  const aggListRequest = instancesClient.aggregatedListAsync({
    project: projectId,
    maxResults: 5,
  });

  console.log('Instances found:');

  // Despite using the `maxResults` parameter, you don't need to handle the pagination
  // yourself. The returned object handles pagination automatically,
  // requesting next pages as you iterate over the results.
  for await (const [zone, instancesObject] of aggListRequest) {
    const instances = instancesObject.instances;

    if (instances && instances.length > 0) {
      console.log(` ${zone}`);
      for (const instance of instances) {
        console.log(` - ${instance.name} (${instance.machineType})`);
      }
    }
  }
}

listAllInstances();

También puedes obtener una lista de instancias en una zona específica:

// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

/**
 * Gets a list of instances created in given project in given zone.
 *
 * @param {string} projectId - ID or number of the project you want to use.
 * @param {string} zone - Name of the zone you want to check, for example: us-west3-b
 */
function main(projectId, zone) {
  /**
   * TODO(developer): Uncomment and replace these variables before running the sample.
   */
  // const projectId = 'YOUR_PROJECT_ID';
  // const zone = 'europe-central2-b'

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

  // List all instances in the given zone in the specified project.
  async function listInstances() {
    const instancesClient = new compute.InstancesClient();

    const [instanceList] = await instancesClient.list({
      project: projectId,
      zone,
    });

    console.log(`Instances found in zone ${zone}:`);

    for (const instance of instanceList) {
      console.log(` - ${instance.name} (${instance.machineType})`);
    }
  }

  listInstances();
}

main(...process.argv.slice(2));

Python

En el siguiente ejemplo, puedes obtener una lista de instancias en todas las zonas de tu proyecto:

Antes de probar esta muestra, sigue las instrucciones de configuración de Python en la Guía de inicio rápido de Compute Engine: Usa las bibliotecas cliente. Si quieres obtener más información, consulta la documentación de referencia de la API de Python de Compute Engine.

Para autenticarte en Compute Engine, configura las credenciales predeterminadas de la aplicación. Si deseas obtener más información, consulta Configura la autenticación para un entorno de desarrollo local.

from __future__ import annotations

from collections import defaultdict
from collections.abc import Iterable

from google.cloud import compute_v1

def list_all_instances(
    project_id: str,
) -> dict[str, Iterable[compute_v1.Instance]]:
    """
    Returns a dictionary of all instances present in a project, grouped by their zone.

    Args:
        project_id: project ID or project number of the Cloud project you want to use.
    Returns:
        A dictionary with zone names as keys (in form of "zones/{zone_name}") and
        iterable collections of Instance objects as values.
    """
    instance_client = compute_v1.InstancesClient()
    request = compute_v1.AggregatedListInstancesRequest()
    request.project = project_id
    # Use the `max_results` parameter to limit the number of results that the API returns per response page.
    request.max_results = 50

    agg_list = instance_client.aggregated_list(request=request)

    all_instances = defaultdict(list)
    print("Instances found:")
    # Despite using the `max_results` parameter, you don't need to handle the pagination
    # yourself. The returned `AggregatedListPager` object handles pagination
    # automatically, returning separated pages as you iterate over the results.
    for zone, response in agg_list:
        if response.instances:
            all_instances[zone].extend(response.instances)
            print(f" {zone}:")
            for instance in response.instances:
                print(f" - {instance.name} ({instance.machine_type})")
    return all_instances

También puedes obtener una lista de instancias en una zona específica:

#  Copyright 2022 Google LLC
#
#  Licensed under the Apache License, Version 2.0 (the "License");
#  you may not use this file except in compliance with the License.
#  You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
#  Unless required by applicable law or agreed to in writing, software
#  distributed under the License is distributed on an "AS IS" BASIS,
#  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#  See the License for the specific language governing permissions and
#  limitations under the License.
# flake8: noqa

# This file is automatically generated. Please do not modify it directly.
# Find the relevant recipe file in the samples/recipes or samples/ingredients
# directory and apply your changes there.

from __future__ import annotations

from collections.abc import Iterable

from google.cloud import compute_v1

def list_instances(project_id: str, zone: str) -> Iterable[compute_v1.Instance]:
    """
    List all instances in the given zone in the specified project.

    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”
    Returns:
        An iterable collection of Instance objects.
    """
    instance_client = compute_v1.InstancesClient()
    instance_list = instance_client.list(project=project_id, zone=zone)

    print(f"Instances found in zone {zone}:")
    for instance in instance_list:
        print(f" - {instance.name} ({instance.machine_type})")

    return instance_list

REST

Obtén una lista agregada de todas las VM en todas las zonas de un proyecto con el método instances.aggregatedList:

GET https://compute.googleapis.com/compute/v1/projects/PROJECT/aggregated/instances

Reemplaza PROJECT por el nombre del proyecto del que deseas obtener una lista de las VM.

Para limitar la lista de las VM a una zona específica, usa el método instances.list:

GET https://compute.googleapis.com/compute/v1/projects/PROJECT/zones/ZONE/instances

Reemplaza lo siguiente:

  • PROJECT: es el nombre del proyecto del que se obtendrá una lista de las VM.

  • ZONE: es la zona de la que deseas obtener una lista de las VM.