Question

I'm currently trying to manipulate the metadata of my instance from the startup-script. To do that I have to use the following command :

gcutil setinstancemetadata <instance-name> --metadata=<key-1:value-1> --fingerprint=<current-fingerprint-hash> 

As you can see the command ask for the instance-name. For I tried to get it from the metadata, but it was not there (see : Default Metadata).

My question is how to get this instance name ?

Edit: For now my only solution is to add the instance-name as a metadata when I create the instance :

gcutil addintance my-cool-instance --metadata=instance-name:my-cool-instance

And then get it with a curl request :

curl 'http://metadata/computeMetadata/v1/instance/attributes/instance-name' -H "X-Google-Metadata-Request: True"
Was it helpful?

Solution 2

The instance name is the same as its hostname, you can just use the $HOSTNAME environmental variable, e.g.:

gcutil setinstancemetadata $HOSTNAME --metadata=<key-1:value-1> --fingerprint=<current-fingerprint-hash>

This works on my instance which was built from the debian-7-wheezy-v20140318 image.

UPDATE: The above works fine on Debian 7 (Wheezy), but on OS's where the HOSTNAME variable is the fully qualified domain name, rather than just the host name, you should use the syntax below:

gcutil setinstancemetadata $($HOSTNAME | cut -d . -f1) --metadata=<key-1:value-1> --fingerprint=<current-fingerprint-hash>

OTHER TIPS

Google Cloud Platform MetaData URL supports getting the instance name via hostname resource, irrespective of any custom hostnames set for the instance. That's why $HOSTNAME is not recommended.

URL1:

INSTANCE_NAME=$(curl http://169.254.169.254/0.1/meta-data/hostname -s | cut -d "." -f1)

URL2:

INSTANCE_NAME=$(curl http://metadata.google.internal/computeMetadata/v1/instance/hostname -H Metadata-Flavor:Google | cut -d . -f1)

GCP follows a common regex pattern for the resource names (?:[a-z](?:[-a-z0-9]{0,61}[a-z0-9])?) , so it's safe to cut the result based on . and use the first part as the instance name.

A better means to get the instance name is to use the hostname command included in the GCE images :

[benoit@my-instance ~]$ hostname
my-instance
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top