16

Is there a way to know from a command line shell if I am currently on a Google Compute Engine machine or somewhere else (development machine)?

4 Answers 4

12
Answer recommended by Google Cloud Collective

Per the metadata docs:

You can easily detect if your applications or scripts are running within a Compute Engine instance by using the metadata server. When you make a request to the server, any response from the metadata server will contain the Metadata-Flavor: Google header. You can look for this header to reliably detect if you are running in Compute Engine.

For example, the following curl request returns a Metadata-Flavor: Google header, indicating that the request is being made from within a Compute Engine instance.

me@my-inst:~$ curl metadata.google.internal -i HTTP/1.1 200 OK Metadata-Flavor: Google Content-Type: application/text Date: Thu, 10 Apr 2014 19:24:27 GMT Server: Metadata Server for VM Content-Length: 22 X-XSS-Protection: 1; mode=block X-Frame-Options: SAMEORIGIN 0.1/ computeMetadata/ 
Sign up to request clarification or add additional context in comments.

Comments

11

Here is python implementation via socket.getaddrinfo

import socket def is_gce_instance(): """Check if it's GCE instance via DNS lookup to metadata server. """ try: socket.getaddrinfo('metadata.google.internal', 80) except socket.gaierror: return False return True 

1 Comment

While this solution works, the downside is that you cannot pass a custom timeout to getaddrinfo, therefore it will hand for about 5 seconds before raising an exception when not running in GAE instance
8

You can also use the dmidecode utility to probe the virtual hardware if you don't want to make a network call:

my@myinst:~$ sudo dmidecode -s bios-vendor | grep Google Google 

1 Comment

This avoids the network call and is therefore more reliable and fast. Additionally, the dmidecode method works for other cloud providers like Digital Ocean, for example.
6

You can also do a DNS lookup for the Metadata server, instead of actually calling it.

For example, doing dig +short metadata.google.internal inside a Google Compute instance would output something like this:

[root@vm-1]# dig +short metadata.google.internal 169.254.169.254 

If, however, you do the same command (dig +short metadata.google.internal) inside a standard server, outside of Google Cloud, you could get an empty response.

So to check, all you need to do (in bash for instance) is:

GMETADATA_ADDR=`dig +short metadata.google.internal` if [[ "${GMETADATA_ADDR}" == "" ]]; then echo "I am NOT in a Google VM!" else echo "I AM INSIDE a Google VM! Whoohoo!" fi 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.