Get the name or ID of the current Google Compute Instance
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
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?