在Python中获取Google Compute Engine实例IP地址的最简单方法是什么?
问题描述:
如果我知道实例的区域和名称,那么获取实例的公共IP地址的最简单方法是什么?
If I know the region and name of an instance, what's the simplest way to get the instance's public IP address?
def get_public_ip(region, instance_name):
# ???
答
使用gcutil:
$ gcutil listinstances --columns=external-ip
或使用python api networkInterfaces
结构如下:
or using python api networkInterfaces
structure looks like:
u'networkInterfaces':[
{
u'accessConfigs':[
{
u'kind':u'compute#accessConfig',
u'type':u'ONE_TO_ONE_NAT',
u'name':u'External NAT',
u'natIP':u'xxx.xxx.xxx.xxx'
}
],
u'networkIP':u'10.xxx.xxx.xxx',
u'network': u'https://www.googleapis.com/compute/v1/projects/<my-project-id>/global/networks/<network-name>',
u'name':u'nic0'
}
]
因此您可以使用此列表实例示例像这样:
so you can use this Listing Instances example to do something like:
for instance in instances:
print instance['networkInterfaces'][0]['accessConfigs'][0]['natIP']