2

How can I get the current running instanceId, and it's zone in the running Python application.

In Go and Java it's done in the following way, what is the equivilant in Python?

Go,

import metadata "cloud.google.com/go/compute/metadata"

func main(){
    println(metadata.InstanceID))
}

Java

String instanceId = com.google.cloud.MetadataConfig.getInstanceId()
aclowkay
  • 3,577
  • 5
  • 35
  • 66
  • 2
    The Metadata Service is not consistently exposed through higher-level language SDKs. However, it's straightforward to construct the HTTP request directly to get the Instance metadata that you need. See here: https://cloud.google.com/compute/docs/storing-retrieving-metadata#project_and_instance_metadata – DazWilkin Jan 20 '19 at 21:11

2 Answers2

6

I found an easy solution:

 requests.get("http://metadata/computeMetadata/v1/instance/id",
         headers={'Metadata-Flavor': 'Google'}).text
aclowkay
  • 3,577
  • 5
  • 35
  • 66
  • More info about querying for vm metadata is available here: https://cloud.google.com/compute/docs/metadata/querying-metadata – forty_two Aug 20 '23 at 06:17
1

In Python it will require a little bit more coding. Here is what you need to do, to list all the instances in Google Compute Engine. Instance's ID and zone.

  1. In Using the Python Client Library documentation you can see the example code for Create, List and Delete an instance. There is also a link to the GitHub for the entire source code.
  2. To list the instances, you need the PROJECT_ID and the ZONE. Which means that you have to list all the available ZONES first and then list all the instances in each ZONE if available. Refer to the Regions and Zones documentation for all the available zones and to Method: zones.list for the Python code to list them.

I did a little bit of coding my self and I have a code that worked for me. You can find my code example here.

NOTE: The code will take some time to execute, since it is looking for all the possible available instances in each available ZONE.

Andrei Cusnir
  • 2,735
  • 1
  • 14
  • 21