Get a list of VMs Stay organized with collections Save and categorize content based on your preferences.
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
- If you haven't already, set upauthentication. Authentication verifies your identity for access to Google Cloud services and APIs. To run code or samples from a local development environment, you can authenticate to Compute Engine by selecting one of the following options:
Select the tab for how you plan to use the samples on this page:
Console
When you use the Google Cloud console to access Google Cloud services and APIs, you don't need to set up authentication.
gcloud
Install the Google Cloud CLI. After installation,initialize the Google Cloud CLI by running the following command:
gcloudinit
If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.
Note: If you installed the gcloud CLI previously, make sure you have the latest version by runninggcloud components update.- Set a default region and zone.
Go
To use the Go samples on this page in a local development environment, install and initialize the gcloud CLI, and then set up Application Default Credentials with your user credentials.
Install the Google Cloud CLI.
If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.
Note: If you installed the gcloud CLI previously, make sure you have the latest version by runninggcloud components update.If you're using a local shell, then create local authentication credentials for your user account:
gcloudauthapplication-defaultlogin
You don't need to do this if you're using Cloud Shell.
If an authentication error is returned, and you are using an external identity provider (IdP), confirm that you have signed in to the gcloud CLI with your federated identity.
For more information, see Set up authentication for a local development environment.
Java
To use the Java samples on this page in a local development environment, install and initialize the gcloud CLI, and then set up Application Default Credentials with your user credentials.
Install the Google Cloud CLI.
If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.
Note: If you installed the gcloud CLI previously, make sure you have the latest version by runninggcloud components update.If you're using a local shell, then create local authentication credentials for your user account:
gcloudauthapplication-defaultlogin
You don't need to do this if you're using Cloud Shell.
If an authentication error is returned, and you are using an external identity provider (IdP), confirm that you have signed in to the gcloud CLI with your federated identity.
For more information, see Set up authentication for a local development environment.
Node.js
To use the Node.js samples on this page in a local development environment, install and initialize the gcloud CLI, and then set up Application Default Credentials with your user credentials.
Install the Google Cloud CLI.
If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.
Note: If you installed the gcloud CLI previously, make sure you have the latest version by runninggcloud components update.If you're using a local shell, then create local authentication credentials for your user account:
gcloudauthapplication-defaultlogin
You don't need to do this if you're using Cloud Shell.
If an authentication error is returned, and you are using an external identity provider (IdP), confirm that you have signed in to the gcloud CLI with your federated identity.
For more information, see Set up authentication for a local development environment.
Python
To use the Python samples on this page in a local development environment, install and initialize the gcloud CLI, and then set up Application Default Credentials with your user credentials.
Install the Google Cloud CLI.
If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.
Note: If you installed the gcloud CLI previously, make sure you have the latest version by runninggcloud components update.If you're using a local shell, then create local authentication credentials for your user account:
gcloudauthapplication-defaultlogin
You don't need to do this if you're using Cloud Shell.
If an authentication error is returned, and you are using an external identity provider (IdP), confirm that you have signed in to the gcloud CLI with your federated identity.
For more information, see Set up authentication for a local development environment.
REST
To use the REST API samples on this page in a local development environment, you use the credentials you provide to the gcloud CLI.
Install the Google Cloud CLI.
If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.
Note: If you installed the gcloud CLI previously, make sure you have the latest version by runninggcloud components update.For more information, seeAuthenticate for using REST in the Google Cloud authentication documentation.
Get a list of VMs
Console
In the Google Cloud console, go to theVM instances page:
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_instancesYou 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_listREST
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 fromZONE: 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.