0

Using python boto API (not Boto3), how to I fetch for the self-instance ID of the CPU running the script in the user-data.

Sam Gomari
  • 733
  • 4
  • 13
  • 37
  • 1
    Possible duplicate of [Find out the instance id from within an ec2 machine](http://stackoverflow.com/questions/625644/find-out-the-instance-id-from-within-an-ec2-machine) – Anthony Neace May 17 '17 at 02:38

1 Answers1

5

Use boto to retrieve the instance ID from the local metadata service, as follows:

import boto.utils
meta = boto.utils.get_instance_metadata()
id = meta['instance-id']
print('instance ID:', id)

Note that boto3 does not include this capability. One option is to simply use the native urllib package to query directly from the metadata service, as follows:

# For python v2
import urllib2
id = urllib2.urlopen('http://169.254.169.254/latest/meta-data/instance-id').read()
print('instance ID:', id)

# For python v3
import urllib.request
id = urllib.request.urlopen('http://169.254.169.254/latest/meta-data/instance-id').read().decode()
print('instance ID:', id)

Alternatively, you could pip install and use adamchainz/ec2-metadata, as follows:

from ec2_metadata import ec2_metadata
print('region:', ec2_metadata.region)
print('instance ID:', ec2_metadata.instance_id)
jarmod
  • 71,565
  • 16
  • 115
  • 122