如何知道一台机器是否是 Google Compute Engine 实例

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

有没有办法从命令行 shell 知道我当前是在 Google Compute Engine 机器还是其他地方(开发机器)?

根据 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/

如果不想打网络电话也可以use the dmidecode utility to probe the virtual hardware:

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

您还可以为元数据服务器执行 DNS 查找,而不是实际调用它。

例如,在 中执行 dig +short metadata.google.internal 一个 Google 计算实例会输出如下内容:

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

但是,如果您在 Google 云之外的标准服务器内执行相同的命令 (dig +short metadata.google.internal),您可能会得到空响应。

所以要检查,您需要做的(例如 bash)是:

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

这里是 python 通过 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