Get the name or id of the current instance of Google Compute

I am running multiple instances of the Google Compute Engine that run Python code, and I want to find the name or identifier of each instance from within the instances.

One solution I found is to get the internal IP address of the instance using:

import socket internal_ip = socket.gethostbyname(socket.gethostname()) 

Then I list all the instances:

 from oauth2client.client import GoogleCredentials from googleapiclient.discovery import build credentials = GoogleCredentials.get_application_default() self.compute = build('compute', 'v1', credentials=credentials) result = self.compute.instances().list(project=project, zone=zone).execute() 

Then I repeat all instances to check if the internal IP matches the instance IP:

 for instance in result["items"]: if instance["networkInterfaces"][0]["networkIP"] == internal_ip: internal_id = instance["id"] 

This works, but it is a bit complicated, is there a more direct way to achieve the same, for example. using the Google Python client library or the gcloud command line tool?

+8
source share
2 answers

Instance Name:

socket.gethostname() or platform.node() should return an instance name. You may need to make out a little depending on your OS.

This worked for me on Debian and Ubuntu systems:

 import socket gce_name = socket.gethostname() 

However, in the CoreOS instance, the hostname command gave the instance name plus zone information, so you have to do some analysis.

Instance ID / Name / Greater (recommended):

The best way to do this is to use a metadata server . This is the easiest way to get information about an instance, and it works with almost any programming language or direct CURL. Here is a Python example using queries .

 import requests metadata_server = "http://metadata/computeMetadata/v1/instance/" metadata_flavor = {'Metadata-Flavor' : 'Google'} gce_id = requests.get(metadata_server + 'id', headers = metadata_flavor).text gce_name = requests.get(metadata_server + 'hostname', headers = metadata_flavor).text gce_machine_type = requests.get(metadata_server + 'machine-type', headers = metadata_flavor).text 

Again, you may need to do some analysis here, but it's really easy!

Links: How can I use Python to get the system hostname?

+17
source

To get the name of your instance, run the following command on your virtual machine:

 curl http://metadata.google.internal/computeMetadata/v1/instance/hostname -H Metadata-Flavor:Google 

and to get your instance ID:

 curl http://metadata.google.internal/computeMetadata/v1/instance/id -H Metadata-Flavor:Google 

Check out the documentation for other available options: https://cloud.google.com/compute/docs/storing-retrieving-metadata#project_and_instance_metadata

0
source

All Articles