How to obtain current instance ID from boto3?

In fact, scrap that answer. All you need is ec2-metadata https://github.com/adamchainz/ec2-metadata

pip3 install ec2-metadata
from ec2_metadata import ec2_metadata
print(ec2_metadata.instance_id)

There is no api for it, no. There is InstanceMetadataFetcher, but it is currently only used to fetch IAM roles for authentication.

Any sort of GET should serve you though. Botocore uses the python requests library which is quite nice.

import requests
response = requests.get('http://169.254.169.254/latest/meta-data/instance-id')
instance_id = response.text

I'm late to the party but after coming across this question and being disappointed that there was no satisfactory boto3 based answer to getting current ec2's instanceid, I set out to fix that.

You get the hostname (which is also the PrivateDnsName) using socket and feed that into a filter on a query to describe_instances and used that to fetch the InstanceId.

import socket
import boto3


session = boto3.Session(region_name="eu-west-1")
ec2_client = session.client('ec2')

hostname = socket.gethostname()

filters = [ {'Name': 'private-dns-name',
            'Values': [ hostname ]}
           ]

response = ec2_client.describe_instances(Filters=filters)["Reservations"]
instanceid = response[0]['Instances'][0]['InstanceId']
print(instanceid)

Your instance will need EC2 read privileges granted via IAM. Policy AmazonEC2ReadOnlyAccess granted to your instance role would work for that.

Tags:

Boto3