View and query VM metadata Stay organized with collections Save and categorize content based on your preferences.
Every virtual machine (VM) stores itsmetadatain directories on a metadata server. Your VM automatically has access to thismetadata server API without any additional authorization.You can use the methods explained in the following sections of this document toview and query VM metadata values:
If you encounter errors when accessing the metadata server, reviewTroubleshooting metadata server access issues.
Pro Tip:Maintenance eventscan cause occasional disruptions to the availability of the metadata server forless than one second. During this time the metadata server might return aError 503 HTTP server response. To make your applications resilientto maintenance events, we recommend that you implement retry logic forapplications that query the metadata server.
Before you begin
- For Windows Server VMs, usePowerShell 3.0 or later. We recommend that you use
ctrl+vto paste the copied code blocks. - Review the basics of how VM metadata for Compute Engine is defined, categorized, and arranged. For more information, seeAbout VM metadata.
- 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.
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.
Required roles
The following roles and permissions are needed to view custom metadata fromoutside the VM by using the Google Cloud console, the Google Cloud CLI, or REST.If you are programmatically querying the metadata from within the VM, youonly need the roles and permissions for connecting to the VM.
To get the permissions that you need to view custom metadata from outside the VM, ask your administrator to grant you the following IAM roles:
- Compute Instance Admin (v1) (
roles/compute.instanceAdmin.v1) on the VM or project - If your VMs use service accounts:Service Account User (
roles/iam.serviceAccountUser) on the service account or project
For more information about granting roles, seeManage access to projects, folders, and organizations.
These predefined roles contain the permissions required to view custom metadata from outside the VM. To see the exact permissions that are required, expand theRequired permissions section:
Required permissions
The following permissions are required to view custom metadata from outside the VM:
- To view custom project metadata:
compute.projects.geton the project - To view custom zonal metadata:
compute.instanceSettings.geton the instance settings in the required zone in the project - To view custom metadata for a VM instance:
compute.instances.geton the VM - If your VMs use service accounts:
iam.serviceAccounts.actAson the service accounts or project
You might also be able to get these permissions withcustom roles or otherpredefined roles.
Programmatically query metadata
You can access all metadata by querying the metadata value entriesprogrammatically from within a Linux or Windows VM. From within your VM, you canprogrammatically query your metadata values in one of the following waysby using tools such ascurl on Linux orInvoke-RestMethod on Windows:
- Query a single metadata entry
- Query a metadata directory listing
- Query metadata changes using the
wait-for-changefeature
Metadata server endpoints
To programmatically query metadata, from within a VM, you have the followingmetadata server endpoints:
- For all VMs, you can query the metadata server by usingthe http endpoint (
http://metadata.google.internal/computeMetadata/v1) or it's IP address(169.254.169.254). Use the IPv4 address even withIPv6-only instances. ForShielded VMs, youcan query the metadata server by using one of the following:
- The http endpoint:
http://metadata.google.internal/computeMetadata/v1 - The https endpoint: (
https://metadata.google.internal/computeMetadata/v1). This https endpoint isavailable inPreview.To see the format for querying the https endpoint, seeQuery metadata by using the HTTPS metadata server endpoint.
- The http endpoint:
Most examples in this document use the http endpoint. However, you can accessall the same metadata entries whether you use the https or the http endpoint.
Parts of a metadata request
The following table summarizes the main parts of a metadata query request.
| Components | Description |
|---|---|
| Root URLs | All metadata values are defined as sub-paths belowthe following root URLs:
|
| Request header | This header indicates that the request was sent with the intention ofretrieving metadata values, rather than unintentionally from an insecure source,and lets the metadata server return the data you requested. If you don't providethis header, the metadata server denies your request. Metadata-Flavor: Google X-Google-Metadata-Request: True header was required inrequests. Both of these headers are still supported, but we recommend thatyou use theMetadata-Flavor header rather than theX-Google-Metadata-Request: True header. |
Query a single metadata entry
Use the following commands to query a single metadata entry.
Linux
- Connect to your Linux VM.
From your Linux VM, use the
curltool to make a query. Toquery for a VM instance or project metadata entry, run the followingcommand:curl "http://metadata.google.internal/computeMetadata/v1/PATH_TO_METADATA_ENTRY" -H "Metadata-Flavor: Google"
Replace the
PATH_TO_METADATA_ENTRYwith the path to the VM instance or project metadata key for which you want to query the value. If the key is in a sub-directory of the instance or project directory, ensure to also include the sub-directory. For example:- To view the
project-idmetadata key, which is stored in project metadata, specifyproject/project-id. - To view the
imagemetadata key, which is stored in VM instance metadata, specifyinstance/image. - To view the
enable-osloginwhich can be stored in the attributes sub-directory of either project or VM instance metadata, specify eitherproject/attributes/enable-osloginorinstance/attributes/enable-oslogindepending on your use case.
For example, to query the boot image for the VM, run the following query:
user@myinst:~$curl "http://metadata.google.internal/computeMetadata/v1/instance/image" -H "Metadata-Flavor: Google"The output is similar to the following:
projects/rhel-cloud/global/images/rhel-8-v20210122
- To view the
Windows
- Connect to your Windows VM.
From your Windows VM, use the
Invoke-RestMethodcommand to make a query.To query for a VM instance or project metadata entry, run the followingcommand:$value = (Invoke-RestMethod ` -Headers @{'Metadata-Flavor' = 'Google'} ` -Uri "http://metadata.google.internal/computeMetadata/v1/PATH_TO_METADATA_ENTRY")$valueReplace the
PATH_TO_METADATA_ENTRYwith the path to the VM instance or project metadata key for which you want to query the value. If the key is in a sub-directory of the instance or project directory, ensure to also include the sub-directory. For example:- To view the
project-idmetadata key, which is stored in project metadata, specifyproject/project-id. - To view the
imagemetadata key, which is stored in VM instance metadata, specifyinstance/image. - To view the
enable-osloginwhich can be stored in the attributes sub-directory of either project or VM instance metadata, specify eitherproject/attributes/enable-osloginorinstance/attributes/enable-oslogindepending on your use case.
For example, to query the boot image for the VM, run the following query:
PS C:\>$value = (Invoke-RestMethod ` -Headers @{'Metadata-Flavor' = 'Google'} ` -Uri "http://metadata.google.internal/computeMetadata/v1/instance/image")$valueThe output is similar to the following:
projects/windows-cloud/global/images/windows-server-2019-dc-v20210112
- To view the
Query metadata directory listings
Use the following commands to query metadata directory listings. Directorylistings are metadata entries that contain other metadata keys. Any metadataentry ending in a trailing slash is a directory listing
Linux
Connect to your Linux VM.
To query for a VM instance or project metadata directory,from your Linux VM, run the following command:
curl "http://metadata.google.internal/computeMetadata/v1/PATH_TO_METADATA_DIRECTORY/" -H "Metadata-Flavor: Google"
Replace the
PATH_TO_METADATA_DIRECTORYwith the path to the VM instance or project metadata directory for which you want to recursively query the listings. For example:- To view the
attributesproject metadata directory entry, the path to specify isproject/attributes/. - To view the
disksVM instance metadata directory entry, the path to specify isinstance/disks/.
For example, consider the
disks/entry, which is a directory of disksthat is attached to the VM. To query thedisks/entry, complete thefollowing steps:Run the
curltool command on the disks directory.user@myinst:~$curl "http://metadata.google.internal/computeMetadata/v1/instance/disks/" -H "Metadata-Flavor: Google"The output is similar to the following:
0/1/2/
If you want more information about disk
0/directory, you can thenquery the specific URL for that directory:user@myinst:~$curl "http://metadata.google.internal/computeMetadata/v1/instance/disks/0/" -H "Metadata-Flavor: Google"The output is similar to the following:
device-nameindexmodetype
Then to query the disk type (
type) for disks0/, you can run the following:user@myinst:~$curl "http://metadata.google.internal/computeMetadata/v1/instance/disks/0/type" -H "Metadata-Flavor: Google"The output is similar to the following:
PERSISTENT
- To view the
Windows
Thedisks/ entry is a directory of disks that is attached to the VM.To query the disks entry, complete the following steps:
Connect to your Windows VM.
To query for a VM instance or project metadata directory,from your Windows VM, run the following command:
$value = (Invoke-RestMethod ` -Headers @{'Metadata-Flavor' = 'Google'} ` -Uri "http://metadata.google.internal/computeMetadata/v1/PATH_TO_METADATA_DIRECTORY/")$valueReplace the
PATH_TO_METADATA_DIRECTORYwith the path to the VM instance or project metadata directory for which you want to recursively query the listings. For example:- To view the
attributesproject metadata directory entry, the path to specify isproject/attributes/. - To view the
disksVM instance metadata directory entry, the path to specify isinstance/disks/.
For example, consider the
disks/entry, which is a directory of disksthat is attached to the VM. To query thedisks/entry, complete thefollowing steps:Use the
Invoke-RestMethodcommand on the disks directory.PS C:\>$value = (Invoke-RestMethod ` -Headers @{'Metadata-Flavor' = 'Google'} ` -Uri "http://metadata.google.internal/computeMetadata/v1/instance/disks/")$valueThe output is similar to the following:
0/1/2/
If you want more information about disk
0/directory, you can query thespecific URL for that directory:PS C:\>$value = (Invoke-RestMethod ` -Headers @{'Metadata-Flavor' = 'Google'} ` -Uri "http://metadata.google.internal/computeMetadata/v1/instance/disks/0/")$valueThe output is similar to the following:
device-nameindexmodetype
Then to query the disk type (
type) for disks0/, you can run the following:PS C:\>$value = (Invoke-RestMethod ` -Headers @{'Metadata-Flavor' = 'Google'} ` -Uri "http://metadata.google.internal/computeMetadata/v1/instance/disks/0/type")$valueThe output is similar to the following:
PERSISTENT
- To view the
Recursively query directory listings
If you want to return all contents under a directory, use therecursive=truequery parameter with your request:
Linux
Connect to your Linux VM.
From your Linux VM, use the
curltool to make a query. To recursively query the listings for a VM instance orproject metadata directory, run the following command:curl "http://metadata.google.internal/computeMetadata/v1/PATH_TO_METADATA_DIRECTORY/?recursive=true" -H "Metadata-Flavor: Google"
Replace the
PATH_TO_METADATA_DIRECTORYwith the path to the VM instance or project metadata directory for which you want to recursively query the listings. For example:- To view the
attributesproject metadata directory entry, the path to specify isproject/attributes/. - To view the
disksVM instance metadata directory entry, the path to specify isinstance/disks/.
For example, the following command recursively queries the instancemetadata listings for the
disks/directory.user@myinst:~$curl "http://metadata.google.internal/computeMetadata/v1/instance/disks/?recursive=true" -H "Metadata-Flavor: Google"The output is similar to the following:
[{"deviceName":"boot","index":0,"mode":"READ_WRITE","type":"PERSISTENT"}, {"deviceName":"persistent-disk-1","index":1,"mode":"READ_WRITE","type":"PERSISTENT"}, {"deviceName":"persistent-disk-2","index":2,"mode":"READ_ONLY","type":"PERSISTENT"}]By default, recursive contents are returned in JSON format. If you want toreturn these contents in text format, append the
alt=textquery parameter:user@myinst:~$curl "http://metadata.google.internal/computeMetadata/v1/instance/disks/?recursive=true&alt=text" -H "Metadata-Flavor: Google"The output is similar to the following:
0/device-name boot 0/index 0 0/mode READ_WRITE 0/type PERSISTENT 1/device-name persistent-disk-1 1/index 1 1/mode READ_WRITE 1/type PERSISTENT 2/device-name persistent-disk-1 2/index 2 2/mode READ_ONLY 2/type PERSISTENT
- To view the
Windows
Connect to your Windows VM.
From your Windows VM, use the
Invoke-RestMethodcommand to make aquery. To recursively query the listings for a VM instance or projectmetadata directory, run the following command:$value = (Invoke-RestMethod
-Headers @{'Metadata-Flavor' = 'Google'}-Uri "http://metadata.google.internal/computeMetadata/v1/PATH_TO_METADATA_DIRECTORY/?recursive=true") $valueReplace the
PATH_TO_METADATA_DIRECTORYwith the path to the VM instance or project metadata directory for which you want to recursively query the listings. For example:- To view the
attributesproject metadata directory entry, the path to specify isproject/attributes/. - To view the
disksVM instance metadata directory entry, the path to specify isinstance/disks/.
For example, the following command recursively queries the instancemetadata listings for the
disks/directory.PS C:\>$value = (Invoke-RestMethod ` -Headers @{'Metadata-Flavor' = 'Google'} ` -Uri "http://metadata.google.internal/computeMetadata/v1/instance/disks/?recursive=true")$valueThe output is similar to the following:
[{"deviceName":"boot","index":0,"mode":"READ_WRITE","type":"PERSISTENT"},{"deviceName":"persistent-disk-1","index":1,"mode":"READ_WRITE","type":"PERSISTENT"},{"deviceName":"persistent-disk-2","index":2,"mode":"READ_ONLY","type":"PERSISTENT"}]By default, recursive contents are returned in JSON format. If you want toreturn these contents in text format, append the
alt=textquery parameter:PS C:\>$value = (Invoke-RestMethod ` -Headers @{'Metadata-Flavor' = 'Google'} ` -Uri "http://metadata.google.internal/computeMetadata/v1/instance/disks/?recursive=true&alt=text")$valueThe output is similar to the following:
0/device-name boot0/index 00/mode READ_WRITE0/type PERSISTENT1/device-name persistent-disk-11/index 11/mode READ_WRITE1/type PERSISTENT2/device-name persistent-disk-12/index 22/mode READ_ONLY2/type PERSISTENT
- To view the
Format query output
By default, each endpoint has a predefined format for the response. Some endpointsmight return data in JSON format by default, while other endpoints might returndata as a string. You can override the default data format specification byusing thealt=json oralt=text query parameters, which return data in JSONstring format or as a plain text representation, respectively.
Linux
- Connect to your Linux VM.
From your Linux VM, use the
curltool to make a query. To change the query response data format for a VMinstance or project metadata entry, run the following command:curl "http://metadata.google.internal/computeMetadata/v1/PATH_TO_METADATA_ENTRY?alt=DATA_FORMAT" -H "Metadata-Flavor: Google"
Replace the following:
Replace the
PATH_TO_METADATA_ENTRYwith the path to the VM instance or project metadata key for which you want to query the value. If the key is in a sub-directory of the instance or project directory, ensure to also include the sub-directory. For example:- To view the
project-idmetadata key, which is stored in project metadata, specifyproject/project-id. - To view the
imagemetadata key, which is stored in VM instance metadata, specifyinstance/image. - To view the
enable-osloginwhich can be stored in the attributes sub-directory of either project or VM instance metadata, specify eitherproject/attributes/enable-osloginorinstance/attributes/enable-oslogindepending on your use case.
- To view the
DATA_FORMAT: the format in which you wantthe query response data—for example,textorjson.
Example
For example, thetags keyautomatically returns data in JSON format. You can return data in textformat instead, by specifying thealt=text query parameter.
Default query
user@myinst:~$curl "http://metadata.google.internal/computeMetadata/v1/instance/tags" -H "Metadata-Flavor: Google"The output is similar to the following:
["http-server", "db-client", "app-server", "mysql-server"]
Query with formatting
user@myinst:~$curl "http://metadata.google.internal/computeMetadata/v1/instance/tags?alt=text" -H "Metadata-Flavor: Google"The output is similar to the following:
http-server db-client app-server mysql-server
Windows
- Connect to your Windows VM.
From your Windows VM, use the
Invoke-RestMethodcommand to make aquery. To change the query response data format for a VM instance orproject metadata entry, run the following command:$value = (Invoke-RestMethod
-Headers @{'Metadata-Flavor' = 'Google'}-Uri "http://metadata.google.internal/computeMetadata/v1/PATH_TO_METADATA_ENTRY?alt=DATA_FORMAT") $valueReplace the following:
Replace the
PATH_TO_METADATA_ENTRYwith the path to the VM instance or project metadata key for which you want to query the value. If the key is in a sub-directory of the instance or project directory, ensure to also include the sub-directory. For example:- To view the
project-idmetadata key, which is stored in project metadata, specifyproject/project-id. - To view the
imagemetadata key, which is stored in VM instance metadata, specifyinstance/image. - To view the
enable-osloginwhich can be stored in the attributes sub-directory of either project or VM instance metadata, specify eitherproject/attributes/enable-osloginorinstance/attributes/enable-oslogindepending on your use case.
- To view the
DATA_FORMAT: the format in which you wantthe query response data—for example,textorjson.
Example
For example, thetags keyautomatically returns data in JSON format. You can return data in textformat instead, by specifying thealt=text query parameter.
Default query
PS C:> $value = (Invoke-RestMethod-Headers @{'Metadata-Flavor' = 'Google'} -Uri "http://metadata.google.internal/computeMetadata/v1/instance/tags") $valueThe output is similar to the following:
["http-server", "db-client", "app-server", "mysql-server"]
Query with formatting
PS C:> $value = (Invoke-RestMethod-Headers @{'Metadata-Flavor' = 'Google'} -Uri "http://metadata.google.internal/computeMetadata/v1/instance/tags?alt=text") $valueThe output is similar to the following:
http-server db-client app-server mysql-server
Query metadata changes using thewait-for-change feature
Given that metadata values can change while your VM is running, themetadata server can be notified of metadata changes by using thewait-for-change feature. With this option, the request only returns anoutput when your specified metadata has changed.
You can use this feature on custom metadata or server-defined metadata, so ifanything changes about your VM or project, or if someone updates a custommetadata entry, you can programmatically react to the change.
For example, you can perform arequest on thetags key so that the request only returns if the contents ofthe tags metadata has changed. When the request returns, it provides the newvalue of that metadata key.
Thewait-for-change feature also lets youmatch with your request andset timeouts.
When working with thewait-for-change feature, consider the following:
You can only perform a
wait-for-changerequest on ametadata endpoint or recursively on the contents of a directory. You cannotperform await-for-changerequest on a directory listing.If you try to do this, the metadata server fails your request and returns a400 Invalid Request error.You cannot perform a
wait-for-changerequest for a serviceaccount token. If you try to make await-for-changerequest to the serviceaccount token URL, the request fails immediately and returns a400 Invalid Request error.
To perform await-for-change request, query a metadata key and append the?wait_for_change=true query parameter:
Linux
- Connect to your Linux VM.
From your Linux VM, use the
curltool to make a query. To perform await-for-changerequest for a VM instanceor project metadata entry, run the following command:curl "http://metadata.google.internal/computeMetadata/v1/PATH_TO_METADATA_ENTRY?wait_for_change=true" -H "Metadata-Flavor: Google"
Replace the
PATH_TO_METADATA_ENTRYwith the path to the VM instance or project metadata key for which you want to query the value. If the key is in a sub-directory of the instance or project directory, ensure to also include the sub-directory. For example:- To view the
project-idmetadata key, which is stored in project metadata, specifyproject/project-id. - To view the
imagemetadata key, which is stored in VM instance metadata, specifyinstance/image. - To view the
enable-osloginwhich can be stored in the attributes sub-directory of either project or VM instance metadata, specify eitherproject/attributes/enable-osloginorinstance/attributes/enable-oslogindepending on your use case.
After there is a change to the specified metadata key, the query returnswith the new value.
- To view the
Examples
In this example, if a request is made to thesetInstanceTags method, therequest returns with the new values:
user@myinst:~$curl "http://metadata.google.internal/computeMetadata/v1/instance/tags?wait_for_change=true" -H "Metadata-Flavor: Google"The output is similar to the following:
http-server db-client
You can also perform await-for-change request recursively on thecontents of a directory:
user@myinst:~$curl "http://metadata.google.internal/computeMetadata/v1/instance/attributes/?recursive=true&wait_for_change=true" -H "Metadata-Flavor: Google"The metadata server returns the new contents if there is any change:
{"foo":"bar","baz":"bat"}Windows
- Connect to your Windows VM.
From your Windows VM, use the
Invoke-RestMethodcommand to make aquery. To perform await-for-changerequest for a VM instance or projectmetadata entry, run the following command:$value = (Invoke-RestMethod ` -Headers @{'Metadata-Flavor' = 'Google'} ` -Uri "http://metadata.google.internal/computeMetadata/v1/PATH_TO_METADATA_ENTRY?wait_for_change=true")$valueReplace the
PATH_TO_METADATA_ENTRYwith the path to the VM instance or project metadata key for which you want to query the value. If the key is in a sub-directory of the instance or project directory, ensure to also include the sub-directory. For example:- To view the
project-idmetadata key, which is stored in project metadata, specifyproject/project-id. - To view the
imagemetadata key, which is stored in VM instance metadata, specifyinstance/image. - To view the
enable-osloginwhich can be stored in the attributes sub-directory of either project or VM instance metadata, specify eitherproject/attributes/enable-osloginorinstance/attributes/enable-oslogindepending on your use case.
After there is a change to the specified metadata key, the query returnswith the new value.
- To view the
Examples
After there is a change to the specified metadata key, the query returnswith the new value. In this example, if a request is made to thesetInstanceTags method, the request returns with the new values:
PS C:> $value = (Invoke-RestMethod-Headers @{'Metadata-Flavor' = 'Google'} -Uri "http://metadata.google.internal/computeMetadata/v1/instance/tags?wait_for_change=true") $valueThe output is similar to the following:
http-server db-client
You can also perform await-for-change request recursively on the contents of adirectory:
PS C:> $value = (Invoke-RestMethod-Headers @{'Metadata-Flavor' = 'Google'} -Uri "http://metadata.google.internal/computeMetadata/v1/instance/attributes?recursive=true&wait_for_change=true") $valueThe metadata server returns the new contents if there is any change:
{"foo":"bar","baz":"bat"}Use ETags
When you submit await-for-change query, the metadata server returns aresponse if anything has changed in the contents of that metadata. However,there is an inherent race condition between a metadata update and await-for-change request being issued, so it's useful to have a reliable way toknow you are getting the latest metadata value.
To help with this, you can use thelast_etag query parameter, which comparesthe ETag value you provide with the ETag value saved on the metadata server. Ifthe ETag values match, then thewait-for-change request is accepted. If theETag values don't match, this indicates that the contents of the metadata haschanged since the last time you retrieved the ETag value, and the metadataserver returns immediately with this latest value.
Linux VMs
To get the current ETag value for a metadata key, complete the followingsteps:
- Connect to your Linux VM.
Make a request to that key and print the headers. To do this, use the
curltool with the-vflag.To get the current ETag for a VM instance or project metadata entry, runthe following command:curl -v "http://metadata.google.internal/computeMetadata/v1/PATH_TO_METADATA_ENTRY" -H "Metadata-Flavor: Google"
Replace the
PATH_TO_METADATA_ENTRYwith the path to the VM instance or project metadata key for which you want to query the value. If the key is in a sub-directory of the instance or project directory, ensure to also include the sub-directory. For example:- To view the
project-idmetadata key, which is stored in project metadata, specifyproject/project-id. - To view the
imagemetadata key, which is stored in VM instance metadata, specifyinstance/image. - To view the
enable-osloginwhich can be stored in the attributes sub-directory of either project or VM instance metadata, specify eitherproject/attributes/enable-osloginorinstance/attributes/enable-oslogindepending on your use case.
For example, the following command gets the current ETag value for the
tagsinstance metadata key.user@myinst:~$curl -v "http://metadata.google.internal/computeMetadata/v1/instance/tags" -H "Metadata-Flavor: Google"The output is similar to the following:
* About to connect() to metadata port 80 (#0)* Trying 169.254.169.254... connected* Connected to metadata (169.254.169.254) port 80 (#0)> GET /computeMetadata/v1/instance/tags HTTP/1.1> User-Agent: curl/7.19.7 (x86_64-pc-linux-gnu) libcurl/7.19.7 OpenSSL/0.9.8k zlib/1.2.3.3 libidn/1.15> Host: metadata> Accept: */*>< HTTP/1.1 200 OK< Content-Type: application/text<ETag: 411261ca6c9e654e< Date: Wed, 13 Feb 2013 22:43:45 GMT< Server: Metadata Server for VM< Content-Length: 26< X-XSS-Protection: 1; mode=block< X-Frame-Options: SAMEORIGIN<http-serverdb-client
- To view the
You can then use that ETag value with the
curltool command in yourwait-for-changerequest. To use the ETag value for thewait-for-changerequest of instance or project metadata, run thefollowing command:curl "http://metadata.google.internal/computeMetadata/v1/PATH_TO_METADATA_ENTRY?wait_for_change=true&last_etag=ETAG" -H "Metadata-Flavor: Google"
Replace the following:
Replace the
PATH_TO_METADATA_ENTRYwith the path to the VM instance or project metadata key for which you want to query the value. If the key is in a sub-directory of the instance or project directory, ensure to also include the sub-directory. For example:- To view the
project-idmetadata key, which is stored in project metadata, specifyproject/project-id. - To view the
imagemetadata key, which is stored in VM instance metadata, specifyinstance/image. - To view the
enable-osloginwhich can be stored in the attributes sub-directory of either project or VM instance metadata, specify eitherproject/attributes/enable-osloginorinstance/attributes/enable-oslogindepending on your use case.
- To view the
ETAG: the ETag value for the metadata key.
In this example, the following command uses the ETag value for the
tagskey and queries for the instance metadata entry.user@myinst:~$curl "http://metadata.google.internal/computeMetadata/v1/instance/tags?wait_for_change=true&last_etag=411261ca6c9e654e" -H "Metadata-Flavor: Google"The metadata server matches your specified ETag value, and if that valuechanges, the request returns with the new contents of your metadata key.
Windows VMs
To get the current ETag value for a metadata key, complete the followingsteps:
- Connect to your Windows VM.
Make a request to that key and print the headers. On Windows, use the
Invoke-WebRequestcommand.To get the current ETag for a VM instance or project metadata entry, runthe following command:$value = (Invoke-WebRequest -Headers @{'Metadata-Flavor' = 'Google'} ` -Uri http://metadata.google.internal/computeMetadata/v1/PATH_TO_METADATA_ENTRY)$value.Headers.ETag
Replace the
PATH_TO_METADATA_ENTRYwith the path to the VM instance or project metadata key for which you want to query the value. If the key is in a sub-directory of the instance or project directory, ensure to also include the sub-directory. For example:- To view the
project-idmetadata key, which is stored in project metadata, specifyproject/project-id. - To view the
imagemetadata key, which is stored in VM instance metadata, specifyinstance/image. - To view the
enable-osloginwhich can be stored in the attributes sub-directory of either project or VM instance metadata, specify eitherproject/attributes/enable-osloginorinstance/attributes/enable-oslogindepending on your use case.
For example, the following command gets the current ETag value for the
tagsinstance metadata key.PS C:> $value = (Invoke-WebRequest -Headers @{'Metadata-Flavor' = 'Google'} ` -Uri http://metadata.google.internal/computeMetadata/v1/instance/tags)
$value.Headers.ETag
The output is similar to the following:
* About to connect() to metadata port 80 (#0) * Trying 169.254.169.254... connected * Connected to metadata (169.254.169.254) port 80 (#0) > GET /computeMetadata/v1/instance/tags HTTP/1.1 > User-Agent: curl/7.19.7 (x86_64-pc-linux-gnu) libcurl/7.19.7 OpenSSL/0.9.8k zlib/1.2.3.3 libidn/1.15 > Host: metadata > Accept:/ > < HTTP/1.1 200 OK < Content-Type: application/text <ETag: 411261ca6c9e654e < Date: Wed, 13 Feb 2013 22:43:45 GMT < Server: Metadata Server for VM < Content-Length: 26 < X-XSS-Protection: 1; mode=block < X-Frame-Options: SAMEORIGIN < http-server db-client
- To view the
You can then use that ETag value in your
wait-for-changerequest. Touse the ETag value for thewait-for-changerequest of instance orproject metadata, run the following command:$value = (Invoke-RestMethod
-Headers @{'Metadata-Flavor' = 'Google'}-Uri "http://metadata.google.internal/computeMetadata/v1/PATH_TO_METADATA_ENTRY?wait_for_change=true&last_etag=ETAG") $valueReplace the following:
Replace the
PATH_TO_METADATA_ENTRYwith the path to the VM instance or project metadata key for which you want to query the value. If the key is in a sub-directory of the instance or project directory, ensure to also include the sub-directory. For example:- To view the
project-idmetadata key, which is stored in project metadata, specifyproject/project-id. - To view the
imagemetadata key, which is stored in VM instance metadata, specifyinstance/image. - To view the
enable-osloginwhich can be stored in the attributes sub-directory of either project or VM instance metadata, specify eitherproject/attributes/enable-osloginorinstance/attributes/enable-oslogindepending on your use case.
- To view the
ETAG: the ETag value for the metadata key.
In this example, the following command uses the ETag value for the
tagskey and queries for the instance metadata entry.PS C:> $value = (Invoke-RestMethod
-Headers @{'Metadata-Flavor' = 'Google'}-Uri "http://metadata.google.internal/computeMetadata/v1/instance/tags?wait_for_change=true&last_etag=411261ca6c9e654e") $valueThe metadata server matches your specified ETag value, and if that valuechanges, the request returns with the new contents of your metadata key.
Python
The following Python sample shows how to programmatically watch themetadata server for changes.
This sample sets the initial ETag to0. The metadata server doesn'treturn a response with0 as the ETag value. When0 is specified as thelast ETag in a request, the metadata server responds with the current valueand ETag. This saves a bit of the code needed to get the initial value andETag.
last_etag="0"whileTrue:r=requests.get(url,params={"last_etag":last_etag,"wait_for_change":True},headers=METADATA_HEADERS,)# During maintenance the service can return a 503, so these should# be retried.ifr.status_code==503:time.sleep(1)continuer.raise_for_status()last_etag=r.headers["etag"]Set timeouts
If you would like yourwait-for-change request to time out after a certainnumber of seconds, you can set thetimeout_sec parameter. Thetimeout_secparameter limits the wait time of your request to the number of seconds you specified,and when the request reaches that limit, itreturns the current contents of the metadata key.
When you set thetimeout_sec parameter, the request always returns after thespecified number of seconds, whether or not the metadata value has actuallychanged. It is only possible to set an integer value for your timeout.
Linux
- Connect to your Linux VM.
From your Linux VM, use the
curltool to make a query. To perform await-for-changerequest with a time outvalue for a VM instance or project metadata entry, run the followingcommand:curl "http://metadata.google.internal/computeMetadata/v1/PATH_TO_METADATA_ENTRY?wait_for_change=true&timeout_sec=TIMEOUT" -H "Metadata-Flavor: Google"
Replace the following:
Replace the
PATH_TO_METADATA_ENTRYwith the path to the VM instance or project metadata key for which you want to query the value. If the key is in a sub-directory of the instance or project directory, ensure to also include the sub-directory. For example:- To view the
project-idmetadata key, which is stored in project metadata, specifyproject/project-id. - To view the
imagemetadata key, which is stored in VM instance metadata, specifyinstance/image. - To view the
enable-osloginwhich can be stored in the attributes sub-directory of either project or VM instance metadata, specify eitherproject/attributes/enable-osloginorinstance/attributes/enable-oslogindepending on your use case.
- To view the
TIMEOUT: the time out value.
For example, the following command performs await-for-change request thatis set to time out after 360 seconds:
user@myinst:~$curl "http://metadata.google.internal/computeMetadata/v1/instance/tags?wait_for_change=true&timeout_sec=360" -H "Metadata-Flavor: Google"Windows
- Connect to your Windows VM.
From your Windows VM, use the
Invoke-RestMethodcommand to make a query.To perform await-for-changerequest with a time out value for a VMinstance or project metadata entry, run the following command:$value = (Invoke-RestMethod
-Headers @{'Metadata-Flavor' = 'Google'}-Uri "http://metadata.google.internal/computeMetadata/v1/PATH_TO_METADATA_ENTRY?wait_for_change=true&timeout_sec=TIMEOUT") $valueReplace the following:
Replace the
PATH_TO_METADATA_ENTRYwith the path to the VM instance or project metadata key for which you want to query the value. If the key is in a sub-directory of the instance or project directory, ensure to also include the sub-directory. For example:- To view the
project-idmetadata key, which is stored in project metadata, specifyproject/project-id. - To view the
imagemetadata key, which is stored in VM instance metadata, specifyinstance/image. - To view the
enable-osloginwhich can be stored in the attributes sub-directory of either project or VM instance metadata, specify eitherproject/attributes/enable-osloginorinstance/attributes/enable-oslogindepending on your use case.
- To view the
TIMEOUT: the time out value.
For example, the following command performs await-for-change request thatis set to time out after 360 seconds:
PS C:> $value = (Invoke-RestMethod-Headers @{'Metadata-Flavor' = 'Google'} -Uri "http://metadata.google.internal/computeMetadata/v1/instance/tags?wait_for_change=true&timeout_sec=360") $valueQuery metadata by using the HTTPS metadata server endpoint
The HTTPS metadata server endpoint (https://metadata.google.internal/computeMetadata/v1) provides addedsecurity for transmission of information between the metadata server and the VM.
To use the HTTPS metadata server endpoint, the VM must meet the followingrequirements:
- The guest environment must berunning on the VM.
- The
disable-https-mds-setupmetadata key for the VM must beset toFALSE. - The VM must be a Shielded VM. This is because the HTTPSmetadata server requires the use of Unified ExtensibleFirmware Interface (UEFI) and Virtual Trusted Platform Module (vTPM) forverifying certificates.
For an overview of how queries to the HTTPS metadata server endpoint arehandled, seeHTTPS metadata server endpoint.You can perform all the same queries to the metadata server whether you use thehttps or the http endpoint. However, to call the https endpoint youmust specify the path to the client identity certificates and in some cases theroot certificate.
The following commands demonstrate how to query the metadata server by using thehttps endpoint.
Linux
Connect to your Linux VM.
From your Linux VM, use the
curltool to make a query andspecify the client identity certificate. Optionally, you can also specifythe root certificate.curl "https://metadata.google.internal/computeMetadata/v1/PATH_TO_METADATA_ENTRY" \ -ECLIENT_CERTIFICATE \ [--cacertROOT_CERTIFICATE] \ -H "Metadata-Flavor: Google"
Replace the following:
Replace the
PATH_TO_METADATA_ENTRYwith the path to the VM instance or project metadata key for which you want to query the value. If the key is in a sub-directory of the instance or project directory, ensure to also include the sub-directory. For example:- To view the
project-idmetadata key, which is stored in project metadata, specifyproject/project-id. - To view the
imagemetadata key, which is stored in VM instance metadata, specifyinstance/image. - To view the
enable-osloginwhich can be stored in the attributes sub-directory of either project or VM instance metadata, specify eitherproject/attributes/enable-osloginorinstance/attributes/enable-oslogindepending on your use case.
- To view the
CLIENT_CERTIFICATE: the path to theclient identity certificate:/run/google-mds-mtls/client.key.- Optional:
ROOT_CERTIFICATE: the path to theroot certificate:/run/google-mds-mtls/root.crt. You must specify thisvalue if the root certificate isn't added to the OS trust store.
For example, to query the boot image for a VM, run the followingquery:
user@myinst:~$curl "https://metadata.google.internal/computeMetadata/v1/instance/image" \ -E /run/google-mds-mtls/client.key \ -H "Metadata-Flavor: Google"The output is similar to the following:
projects/rhel-cloud/global/images/rhel-8-v20210122
If you see an error message, review thetroubleshooting documentation.
Windows
Connect to your Windows VM.
Get theclient identity certificateby using one of the following commands:
$cert = Get-PfxCertificate -FilePath "C:\ProgramData\Google\Compute Engine\mds-mtls-client.key.pfx"
$cert = Get-ChildItem Cert:\LocalMachine\My | Where-Object { $_.Issuer -like "google.internal" }
From your Windows VM, use the
Invoke-RestMethodcommand and specify the client identitycertificate to make a query.PS C:\>$value = (Invoke-RestMethod ` -Headers @{'Metadata-Flavor' = 'Google'} -CertificateCLIENT_CERTIFICATE ` -Uri "https://metadata.google.internal/computeMetadata/v1/PATH_TO_METADATA_ENTRY")$valueReplace the following:
CLIENT_CERTIFICATE: the path to theclient identity certificateon the VM. This is the$certvariable that is set in the previous step.Replace the
PATH_TO_METADATA_ENTRYwith the path to the VM instance or project metadata key for which you want to query the value. If the key is in a sub-directory of the instance or project directory, ensure to also include the sub-directory. For example:- To view the
project-idmetadata key, which is stored in project metadata, specifyproject/project-id. - To view the
imagemetadata key, which is stored in VM instance metadata, specifyinstance/image. - To view the
enable-osloginwhich can be stored in the attributes sub-directory of either project or VM instance metadata, specify eitherproject/attributes/enable-osloginorinstance/attributes/enable-oslogindepending on your use case.
- To view the
For example, to query the boot image for a Windows server 2019 VM, runthe following query:
PS C:\>$value = (Invoke-RestMethod ` -Headers @{'Metadata-Flavor' = 'Google'} -Certificate $cert ` -Uri "https://metadata.google.internal/computeMetadata/v1/instance/image")$valueThe output is similar to the following:
projects/windows-cloud/global/images/windows-server-2019-dc-v20210112
Limitations
Any requests that contain the header
X-Forwarded-Forareautomatically rejected by the metadata server. This header generallyindicates that the request was proxied and might not be a request made by anauthorized user. For security reasons, all such requests are rejected.When you use the
curlcommand to retrieve metadata from the server, note thatsome encoded characters aren't supported in the request path.Encoded characters are only supported in the query path.For example, the following request might not work:
curl "http://metadata.google.internal/computeMetadata/v1/instance/service-accounts/123456789-compute%40developer.gserviceaccount.com/?query_path=https%3A%2F%2Flocalhost%3A8200%2Fexample%2Fquery&another_param=true" -H "Metadata-Flavor: Google"
For this request to work, you must replace the unsupported encoded characterin the request path (
%40) with the equivalent accepted value (@).curl "http://metadata.google.internal/computeMetadata/v1/instance/service-accounts/1234567898-compute@developer.gserviceaccount.com/?query_path=https%3A%2F%2Flocalhost%3A8200%2Fexample%2Fquery&another_param=true" -H "Metadata-Flavor: Google"
The following table summarises the encoded characters that aren't supported ina request path.
Encoded character Accepted value %21 !
%24 $
%27 '
%28 (
%29 )
%2A *
%2C ,
%40 @
Status codes
When you make a request to the metadata server, the metadata server returnsstandard HTTP status codes to indicate success or failure. Sometimes,network conditions or host events can cause the metadata server to fail your requestand return an error code. In these cases, you should design your application to befault-tolerant and to be able to recognize and handle these errors.
For a detailed list of status codes that can be returned, seeTroubleshoot server codes.
View the custom metadata for your VMs
You can view the custom metadata values for your Compute Engine VMs in one ofthe following ways:
View project metadata
To view custom metadata that applies to all VMs in your project, use oneof the following methods.
Console
In the Google Cloud console, go to theMetadata page.
On theMetadata page, you see a list of all custom project metadataentries for your project.
gcloud
Use thegcloud compute project-info describe commandto query project metadata:
gcloud compute project-info describe --flatten="commonInstanceMetadata[]"
The output is similar to the following:
---fingerprint: HcSFdS_1_1I=items:- key: ssh-keys value:USERNAME:ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDWZ...kind: compute#metadata
REST
To query project metadata, create aGET request to theproject.get method.
ReplacePROJECT_ID with your project ID.
GET https://compute.googleapis.com/compute/v1/projects/PROJECT_ID
The output is similar to the following:
"kind": "compute#project","id": "XXXXXXX","creationTimestamp": "2018-12-10T08:34:33.616-08:00","name": "YOUR_PROJECT","commonInstanceMetadata": { "kind": "compute#metadata", "fingerprint": "XXXXXCdg=", "items": [ { "key": "enable-guest-attributes", "value": "TRUE" }, { "key": "enable-os-inventory", "value": "true" }, { "key": "enable-osconfig", "value": "TRUE" }, { "key": "enable-oslogin", "value": "TRUE" }, { "key": "sshKeys", "value": "XXXXX" } ]}, ...View zonal metadata
To view custom metadata that applies to all VM instances in a specific zone ina project, use one of the following methods.
gcloud
To query the custom zonal metadata, use thegcloud compute project-zonal-metadata describe command.
gcloud compute project-zonal-metadata describe \ --zone=ZONE \ --project=PROJECT_ID
Replace the following:
PROJECT_ID: your project IDZONE: the zone for which you want to view thezonal metadata.
The output is similar to the following:
{ "fingerprint": "VlRIl8dx9vk=", "metadata": { items: { "key-1": "value-1", "key-2": "value-2" } }}REST
To query the custom zonal metadata, make aGET request to theinstanceSettings().get method
GET https://compute.googleapis.com/compute/v1/projects/PROJECT_ID/zones/ZONE/instanceSettings
Replace the following:
PROJECT_ID: your project IDZONE: the zone for which you want to view thezonal metadata.
The output is similar to the following:
{ "fingerprint": "VlRIl8dx9vk=", "metadata": { items: { "key-1": "value-1", "key-2": "value-2" } }}View instance metadata
To view metadata that applies to a single VM in your project, use one ofthe following methods.
Console
- In the Google Cloud console, go to theVM instances page.
Click the name of the VM for which you want to view metadata.
SSH keys for this VM. In theSecurity and access section,view theSSH keys field.
A value of
Noneindicates there are no SSH keys stored in instancemetadata.Any other value indicates that there are SSH keys stored in instancemetadata.
SSH keys for a project. In theSecurity and access section,view theBlock project-wide SSH keys field.
A value of
Onindicates that the value of the metadata keyblock-project-ssh-keysisTRUEin instance metadata.A value of
Offindicates that the value of the metadata keyblock-project-ssh-keysisFALSE, or that the key isn't set.
All other custom metadata. View theCustom metadata section.You see all custom metadata keys and values, other than SSH keymetadata.
gcloud
Use thegcloud compute instances describe commandto query instance metadata:
gcloud compute instances describeVM_NAME --flatten="metadata[]"
ReplaceVM_NAME with the name of the VM you want tofind metadata for.
The output is similar to the following:
---fingerprint: MTgTJ5m-Cjs=items:- key: enable-oslogin value: 'true'kind: compute#metadata
REST
To query metadata for a specific VM, send aGET request to theinstances.get method.
GET https://compute.googleapis.com/compute/v1/projects/PROJECT_ID/zones/ZONE/instances/VM_NAME
The output is similar to the following:
......"metadata": {"kind": "compute#metadata","fingerprint": "XXXXXXVo=","items": [ { "key": "enable-oslogin", "value": "true" }]},....Replace the following:
PROJECT_ID: your project IDZONE: the zone where the VM is locatedVM_NAME: the name of the VM
What's next
- Learn more aboutVM metadata.
- Learn how toset custom metadata.
- Learn how toset and query guest attributes.
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.