Skip to content Skip to sidebar Skip to footer

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

Solution 1:

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:

forinstanceininstances:
    printinstance['networkInterfaces'][0]['accessConfigs'][0]['natIP']

Solution 2:

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

Post a Comment for "What's The Simplest Way To Get The Ip Address Of A Google Compute Engine Instance In Python?"