How to get current instance id from boto3?

Is there an equivalent

curl http://169.254.169.254/latest/meta-data/instance-id 

with boto3 to get current instance instance instance instance in python?

+12
boto3
source share
2 answers

No api for him, no. There is an InstanceMetadataFetcher , but currently it is only used to obtain the IAM role for authentication.

Any type of GET should serve you. Botocore uses the python requests library, which is pretty nice.

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

There is still no boto3 API for this. But if your current instance is a Linux system, you can use the following python3 code to get 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) 
0
source share

All Articles