Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to know if a machine is an Google Compute Engine instance

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)?

like image 281
poiuytrez Avatar asked Jun 18 '15 09:06

poiuytrez


2 Answers

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/
like image 133
Misha Brukman Avatar answered Sep 19 '22 15:09

Misha Brukman


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


like image 37
northtree Avatar answered Sep 20 '22 15:09

northtree