Obtenir une liste des VM


Pour afficher un résumé des VM en cours d'exécution dans votre projet, obtenez une liste des VM. Ce document explique comment obtenir une liste des VM dans toutes les zones ou dans des zones spécifiques.

Avant de commencer

  • Si ce n'est pas déjà fait, configurez l'authentification. L'authentification est le processus permettant de valider votre identité pour accéder aux services et aux API Google Cloud. Pour exécuter du code ou des exemples depuis un environnement de développement local, vous pouvez vous authentifier auprès de Compute Engine comme suit :

    Sélectionnez l'onglet correspondant à la façon dont vous prévoyez d'utiliser les exemples de cette page :

    Console

    Lorsque vous utilisez la console Google Cloud pour accéder aux services et aux API Google Cloud, vous n'avez pas besoin de configurer l'authentification.

    gcloud

    1. Installez Google Cloud CLI, puis initialisez-la en exécutant la commande suivante :

      gcloud init
    2. Définissez une région et une zone par défaut.

    Go

    Pour utiliser les exemples Go de cette page dans un environnement de développement local, installez et initialisez gcloud CLI, puis configurez le service Identifiants par défaut de l'application à l'aide de vos identifiants utilisateur.

    1. Installez Google Cloud CLI.
    2. Pour initialiser gcloudCLI, exécutez la commande suivante :

      gcloud init
    3. Créez des identifiants d'authentification locaux pour votre compte Google :

      gcloud auth application-default login

    Pour en savoir plus, consultez les sections sur Configurer l'authentification pour un environnement de développement local.

    Java

    Pour utiliser les exemples Java de cette page dans un environnement de développement local, installez et initialisez gcloud CLI, puis configurez le service Identifiants par défaut de l'application à l'aide de vos identifiants utilisateur.

    1. Installez Google Cloud CLI.
    2. Pour initialiser gcloudCLI, exécutez la commande suivante :

      gcloud init
    3. Créez des identifiants d'authentification locaux pour votre compte Google :

      gcloud auth application-default login

    Pour en savoir plus, consultez les sections sur Configurer l'authentification pour un environnement de développement local.

    Node.js

    Pour utiliser les exemples Node.js de cette page dans un environnement de développement local, installez et initialisez gcloud CLI, puis configurez le service Identifiants par défaut de l'application à l'aide de vos identifiants utilisateur.

    1. Installez Google Cloud CLI.
    2. Pour initialiser gcloudCLI, exécutez la commande suivante :

      gcloud init
    3. Créez des identifiants d'authentification locaux pour votre compte Google :

      gcloud auth application-default login

    Pour en savoir plus, consultez les sections sur Configurer l'authentification pour un environnement de développement local.

    Python

    Pour utiliser les exemples Python de cette page dans un environnement de développement local, installez et initialisez gcloud CLI, puis configurez le service Identifiants par défaut de l'application à l'aide de vos identifiants utilisateur.

    1. Installez Google Cloud CLI.
    2. Pour initialiser gcloudCLI, exécutez la commande suivante :

      gcloud init
    3. Créez des identifiants d'authentification locaux pour votre compte Google :

      gcloud auth application-default login

    Pour en savoir plus, consultez les sections sur Configurer l'authentification pour un environnement de développement local.

    REST

    Pour utiliser les exemples d'API REST de cette page dans un environnement de développement local, vous devez utiliser les identifiants que vous fournissez à gcloud CLI.

      Installez Google Cloud CLI, puis initialisez-la en exécutant la commande suivante :

      gcloud init

Obtenir une liste des VM

Console

Dans la console Google Cloud, accédez à la page Instances de VM :

Accéder à la page "Instances de VM"

gcloud

Obtenez une liste d'agrégation de toutes les VM dans toutes les zones d'un projet à l'aide de la commande gcloud compute instances list :

gcloud compute instances list

Pour limiter la liste des VM à une zone spécifique, utilisez la commande précédente avec l'option --zones.

Go

L'exemple suivant permet d'obtenir la liste des instances de toutes les zones de votre projet :

Avant d'essayer cet exemple, suivez les instructions de configuration pour Go décrites dans le Guide de démarrage rapide de Compute Engine à l'aide des bibliothèques clientes. Pour en savoir plus, consultez la documentation de référence de l'API Go Compute Engine.

Pour vous authentifier auprès de Compute Engine, configurez le service Identifiants par défaut de l'application. Pour en savoir plus, consultez Configurer l'authentification pour un environnement de développement 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
}

Vous pouvez également obtenir une liste d'instances dans une zone spécifique :

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

L'exemple suivant permet d'obtenir la liste des instances de toutes les zones de votre projet :

Avant d'essayer cet exemple, suivez les instructions de configuration pour Java décrites dans le Guide de démarrage rapide de Compute Engine à l'aide des bibliothèques clientes. Pour en savoir plus, consultez la documentation de référence de l'API Java Compute Engine.

Pour vous authentifier auprès de Compute Engine, configurez le service Identifiants par défaut de l'application. Pour en savoir plus, consultez Configurer l'authentification pour un environnement de développement 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;
    }
  }

}

Vous pouvez également obtenir une liste d'instances dans une zone spécifique :

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

L'exemple suivant permet d'obtenir la liste des instances de toutes les zones de votre projet :

Avant d'essayer cet exemple, suivez les instructions de configuration pour Node.js décrites dans le Guide de démarrage rapide de Compute Engine à l'aide des bibliothèques clientes. Pour en savoir plus, consultez la documentation de référence de l'API Node.js Compute Engine.

Pour vous authentifier auprès de Compute Engine, configurez le service Identifiants par défaut de l'application. Pour en savoir plus, consultez Configurer l'authentification pour un environnement de développement 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();

Vous pouvez également obtenir une liste d'instances dans une zone spécifique :

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

L'exemple suivant permet d'obtenir la liste des instances de toutes les zones de votre projet :

Avant d'essayer cet exemple, suivez les instructions de configuration pour Python décrites dans le Guide de démarrage rapide de Compute Engine à l'aide des bibliothèques clientes. Pour en savoir plus, consultez la documentation de référence de l'API Python Compute Engine.

Pour vous authentifier auprès de Compute Engine, configurez le service Identifiants par défaut de l'application. Pour en savoir plus, consultez Configurer l'authentification pour un environnement de développement 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

Vous pouvez également obtenir une liste d'instances dans une zone spécifique :

#  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

Obtenez une liste d'agrégation de toutes les VM dans toutes les zones d'un projet à l'aide de la méthode instances.aggregatedList :

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

Remplacez PROJECT par le nom du projet pour lequel vous souhaitez obtenir une liste des VM.

Pour limiter la liste des VM à une zone spécifique, utilisez la méthode instances.list :

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

Remplacez les éléments suivants :

  • PROJECT : nom du projet pour lequel vous souhaitez obtenir une liste des VM

  • ZONE : zone pour laquelle vous souhaitez obtenir une liste des VM