Thomas Johnson
Thomas Johnson

Reputation: 11718

What's the simplest way to get the IP address of a Google Compute Engine Instance in Python?

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

Upvotes: 0

Views: 3085

Answers (2)

Roman
Roman

Reputation: 9461

Try this:

credentials = GoogleCredentials.get_application_default()
api = build('compute', 'v1', credentials=credentials)

response = api.instances().get(project=project_id, zone=region, instance=instance_name).execute()

ip = response['networkInterfaces'][0]['accessConfigs'][0]['natIP']

returns the external IP listed in the compute engine front end

Upvotes: 1

Guy Gavriely
Guy Gavriely

Reputation: 11396

using gcutil:

$ gcutil listinstances --columns=external-ip

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']

Upvotes: 2

Related Questions