Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

google-cloud get instance id and zone with python api

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()
like image 978
aclowkay Avatar asked Sep 18 '26 14:09

aclowkay


2 Answers

I found an easy solution:

 requests.get("http://metadata/computeMetadata/v1/instance/id",
         headers={'Metadata-Flavor': 'Google'}).text
like image 149
aclowkay Avatar answered Sep 21 '26 04:09

aclowkay


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.

like image 25
Andrei Cusnir Avatar answered Sep 21 '26 03:09

Andrei Cusnir



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!