6

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"
Benoît Sauvère
  • 701
  • 7
  • 23

3 Answers3

4

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.

Baskar
  • 1,439
  • 12
  • 17
3

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>
IanGSY
  • 3,664
  • 1
  • 22
  • 40
  • Thank you for your response. On CentOS, the hostname seems a little bit different : `my-cool-instance.c.my-cool-project.xxxx.com.yyyyy`. I just add a `cut` and it is solved. – Benoît Sauvère Mar 25 '14 at 15:07
  • 2
    Not all the time the instance name is same as the hostname. What if you have a custom hostname? The name of the instance is different from the hostname in that case. – Baskar Dec 19 '16 at 23:09
0

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
Benoît Sauvère
  • 701
  • 7
  • 23