How to query AWS using boto3 to find if the IMDSv2 is enforced in an EC2 instance or not

Viewed 909

Is there any function in boto3 that may tell if IMDSV2 is enabled or not ?

1 Answers
import boto3

ec2 = boto3.client('ec2')
instance_id = 'i-xxx'
res = ec2.describe_instances(InstanceIds=[instance_id])
metadata_options = res['Reservations'][0]['Instances'][0]['MetadataOptions']
http_tokens = metadata_options['HttpTokens']
state = metadata_options['State']

if http_tokens == 'required' and state == 'applied':
    print(f"IMDSv2 is enforced in the EC2 instance with id {instance_id}")
else:
    print(f"IMDSv2 is not enforced")
    print(http_tokens, state)
Related