Vasilis
Vasilis

Reputation: 2832

Get the name or ID of the current Google Compute Instance

I'm running a number of Google Compute Engine instances that run Python code, and I want to find the name or the ID of each instance from inside the instances.

One solution I've found is to get the internal IP 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 iterate over all the instances to check if the internal IP matches the IP of an instance:

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

This works but it's a bit complicated, is there a more direct way to achieve the same thing, e.g. using Google's Python Client Library or the gcloud command line tool?

Upvotes: 19

Views: 15084

Answers (2)

sacha
sacha

Reputation: 551

To get your instance name, execute the following from your VM:

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 documentations for other available parameters: https://cloud.google.com/compute/docs/storing-retrieving-metadata#project_and_instance_metadata

Upvotes: 13

Sandeep Dinesh
Sandeep Dinesh

Reputation: 2135

Instance Name:

socket.gethostname() or platform.node() should return the name of the instance. You might have to do a bit of parsing depending on your OS.

This worked for me on Debian and Ubuntu systems:

import socket
gce_name = socket.gethostname()

However, on a CoreOS instance, the hostname command gave the name of the instance plus the zone information, so you would have to do some parsing.

Instance ID / Name / More (Recommended):

The better way to do this is to use the Metadata server. This is the easiest way to get instance information, and works with basically any programming language or straight CURL. Here is a Python example using Requests.

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 might need to do some parsing here, but it is really straightforward!

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

Upvotes: 29

Related Questions