Get a list of VMs

Linux Windows

To view a summary of VMs running in your project, get a list of VMs. This document shows you how to get a list of VMs in all zones or in specificzones.

Before you begin

Get a list of VMs

Console

In the Google Cloud console, go to theVM instances page:

Go to VM instances

gcloud

Get an aggregate list of all VMs in all zones for a project by using thegcloud compute instances listcommand:

gcloud compute instances list

To narrow the list of VMs to a specific zone, use the previous command withthe--zones flag.

Go

The following example get a list of instances across all zones in your project:

Before trying this sample, follow theGo setup instructions in theCompute Engine quickstart using client libraries. For more information, see theCompute EngineGo API reference documentation.

To authenticate to Compute Engine, set up Application Default Credentials. For more information, seeSet up authentication for a local development environment.

import("context""fmt""io"compute"cloud.google.com/go/compute/apiv1"computepb"cloud.google.com/go/compute/apiv1/computepb""google.golang.org/api/iterator""google.golang.org/protobuf/proto")// listAllInstances prints all instances present in a project, grouped by their zone.funclistAllInstances(wio.Writer,projectIDstring)error{// projectID := "your_project_id"ctx:=context.Background()instancesClient,err:=compute.NewInstancesRESTClient(ctx)iferr!=nil{returnfmt.Errorf("NewInstancesRESTClient: %w",err)}deferinstancesClient.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()iferr==iterator.Done{break}iferr!=nil{returnerr}instances:=pair.Value.Instancesiflen(instances) >0{fmt.Fprintf(w,"%s\n",pair.Key)for_,instance:=rangeinstances{fmt.Fprintf(w,"- %s %s\n",instance.GetName(),instance.GetMachineType())}}}returnnil}

You can also get a list instances in a specific zone:

// 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.packagesnippetsimport("context""fmt""io"compute"cloud.google.com/go/compute/apiv1"computepb"cloud.google.com/go/compute/apiv1/computepb""google.golang.org/api/iterator")// listInstances prints a list of instances created in given project in given zone.funclistInstances(wio.Writer,projectID,zonestring)error{// projectID := "your_project_id"// zone := "europe-central2-b"ctx:=context.Background()instancesClient,err:=compute.NewInstancesRESTClient(ctx)iferr!=nil{returnfmt.Errorf("NewInstancesRESTClient: %w",err)}deferinstancesClient.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()iferr==iterator.Done{break}iferr!=nil{returnerr}fmt.Fprintf(w,"- %s %s\n",instance.GetName(),instance.GetMachineType())}returnnil}

Java

The following example get a list of instances across all zones in your project:

Before trying this sample, follow theJava setup instructions in theCompute Engine quickstart using client libraries. For more information, see theCompute EngineJava API reference documentation.

To authenticate to Compute Engine, set up Application Default Credentials. For more information, seeSet up authentication for a local development environment.

importcom.google.cloud.compute.v1.AggregatedListInstancesRequest;importcom.google.cloud.compute.v1.Instance;importcom.google.cloud.compute.v1.InstancesClient;importcom.google.cloud.compute.v1.InstancesClient.AggregatedListPagedResponse;importcom.google.cloud.compute.v1.InstancesScopedList;importjava.io.IOException;importjava.util.Map;publicclassListAllInstances{publicstaticvoidmain(String[]args)throwsIOException{// TODO(developer): Replace these variables before running the sampleStringproject="your-project-id";listAllInstances(project);}// List all instances in the specified project ID.publicstaticAggregatedListPagedResponselistAllInstances(Stringproject)throwsIOException{// 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(InstancesClientinstancesClient=InstancesClient.create()){// Use the `setMaxResults` parameter to limit the number of results// that the API returns per response page.AggregatedListInstancesRequestaggregatedListInstancesRequest=AggregatedListInstancesRequest.newBuilder().setProject(project).setMaxResults(5).build();InstancesClient.AggregatedListPagedResponseresponse=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 zoneStringzone=zoneInstances.getKey();if(!zoneInstances.getValue().getInstancesList().isEmpty()){// zoneInstances.getKey() returns the fully qualified address.// Hence, strip it to get the zone name onlySystem.out.printf("Instances at %s: ",zone.substring(zone.lastIndexOf('/')+1));for(Instanceinstance:zoneInstances.getValue().getInstancesList()){System.out.println(instance.getName());}}}System.out.println("####### Listing all instances complete #######");returnresponse;}}}

You can also get a list instances in a specific zone:

/* * 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. */packagecompute;importcom.google.cloud.compute.v1.Instance;importcom.google.cloud.compute.v1.InstancesClient;importjava.io.IOException;publicclassListInstance{publicstaticvoidmain(String[]args)throwsIOException{// TODO(developer): Replace these variables before running the sampleStringproject="your-project-id";Stringzone="zone-name";listInstances(project,zone);}// List all instances in the given zone in the specified project ID.publicstaticvoidlistInstances(Stringproject,Stringzone)throwsIOException{// 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(InstancesClientinstancesClient=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(InstancezoneInstance:instancesClient.list(project,zone).iterateAll()){System.out.println(zoneInstance.getName());}System.out.println("####### Listing instances complete #######");}}}

Node.js

The following example get a list of instances across all zones in your project:

Before trying this sample, follow theNode.js setup instructions in theCompute Engine quickstart using client libraries. For more information, see theCompute EngineNode.js API reference documentation.

To authenticate to Compute Engine, set up Application Default Credentials. For more information, seeSet up authentication for a local development environment.

/** * TODO(developer): Uncomment and replace these variables before running the sample. */// const projectId = 'YOUR_PROJECT_ID';constcompute=require('@google-cloud/compute');// List all instances in the specified project.asyncfunctionlistAllInstances(){constinstancesClient=newcompute.InstancesClient();//Use the `maxResults` parameter to limit the number of results that the API returns per response page.constaggListRequest=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.forawait(const[zone,instancesObject]ofaggListRequest){constinstances=instancesObject.instances;if(instances &&instances.length >0){console.log(`${zone}`);for(constinstanceofinstances){console.log(` -${instance.name} (${instance.machineType})`);}}}}listAllInstances();

You can also get a list instances in a specific zone:

// 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 */functionmain(projectId,zone){/**   * TODO(developer): Uncomment and replace these variables before running the sample.   */// const projectId = 'YOUR_PROJECT_ID';// const zone = 'europe-central2-b'constcompute=require('@google-cloud/compute');// List all instances in the given zone in the specified project.asyncfunctionlistInstances(){constinstancesClient=newcompute.InstancesClient();const[instanceList]=awaitinstancesClient.list({project:projectId,zone,});console.log(`Instances found in zone${zone}:`);for(constinstanceofinstanceList){console.log(` -${instance.name} (${instance.machineType})`);}}listInstances();}main(...process.argv.slice(2));

Python

The following example get a list of instances across all zones in your project:

Before trying this sample, follow thePython setup instructions in theCompute Engine quickstart using client libraries. For more information, see theCompute EnginePython API reference documentation.

To authenticate to Compute Engine, set up Application Default Credentials. For more information, seeSet up authentication for a local development environment.

from__future__importannotationsfromcollectionsimportdefaultdictfromcollections.abcimportIterablefromgoogle.cloudimportcompute_v1deflist_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=50agg_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.forzone,responseinagg_list:ifresponse.instances:all_instances[zone].extend(response.instances)print(f"{zone}:")forinstanceinresponse.instances:print(f" -{instance.name} ({instance.machine_type})")returnall_instances

You can also get a list instances in a specific zone:

#  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__importannotationsfromcollections.abcimportIterablefromgoogle.cloudimportcompute_v1deflist_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}:")forinstanceininstance_list:print(f" -{instance.name} ({instance.machine_type})")returninstance_list

REST

Get an aggregate list of all VMs in all zones in a project by using theinstances.aggregatedListmethod:

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

ReplacePROJECT with the name of the project to geta list of VMs from.

To narrow the list of VMs to a specific zone, use theinstances.listmethod:

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

Replace the following:

  • PROJECT: the name of the project to get a list ofVMs from

  • ZONE: the zone to get a list of VMs from

Except as otherwise noted, the content of this page is licensed under theCreative Commons Attribution 4.0 License, and code samples are licensed under theApache 2.0 License. For details, see theGoogle Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.

Last updated 2025-12-15 UTC.