'How to obtain current instance ID from boto3?
Is there an equivalent of
curl http://169.254.169.254/latest/meta-data/instance-id
with boto3 to obtain the current running instance instance-id in python?
Solution 1:[1]
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)
Solution 2:[2]
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.
Solution 3:[3]
There is still no boto3 api to do it. But if your current instance is Linux system, then you can use the following python3 code to get the instance_id:
import subprocess
cmd='''set -o pipefail && sudo grep instance-id /run/cloud-init/instance-data.json | head -1 | sed 's/.*\"i-/i-/g' | sed 's/\",//g\''''
status, instance_id = subprocess.getstatusoutput(cmd)
print(status, instance_id)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | David Buck |
| Solution 2 | David Buck |
| Solution 3 |
