Skip to content

Instantly share code, notes, and snippets.

@phwelo
Created August 11, 2022 14:41
Show Gist options
  • Save phwelo/85a571987b74572a77d60e948d485a79 to your computer and use it in GitHub Desktop.
Save phwelo/85a571987b74572a77d60e948d485a79 to your computer and use it in GitHub Desktop.
IMDSv2 for everything - Set metadata to IMDSv2 for all of your ec2 instances
#!/usr/bin/env python3
import boto3
client = boto3.client('ec2')
def set_imdsv2_required(instance_id):
client.modify_instance_metadata_options(
InstanceId=instance_id,
HttpTokens='required',
HttpPutResponseHopLimit=1,
HttpEndpoint='enabled'
)
print("IMDSv2 has been turned on for " + instance_id)
def get_instance_id_list():
response = client.describe_instances()["Reservations"]
for reservation in response:
if reservation["Instances"][0]["State"]["Name"] == "running":
yield reservation["Instances"][0]["InstanceId"]
instances = list(get_instance_id_list())
[set_imdsv2_required(instance) for instance in instances]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment