Saturday, November 25, 2023

IMDSv2

v2 of the AWS "Instance Metadata Service" has been around for a while.

  • It is optional for now, but they will make it mandatory some time during 2024 [1].
  • The IMDS has to do with how EC2 instances get their metadata and IAM permissions.
  • If you're using a recent version of cloud-init, AWS CLI and SDKs, these should support v2.
  • By default, most instances that have been around for a while still use v1.

To list instances that are still using v1 [2]:

aws ec2 describe-instances \
  --filters "Name=metadata-options.http-tokens,Values=optional" \
  --query "Reservations[*].Instances[*].[InstanceId]" \
  --output text

To enable v2 on a per-instance basis:

aws ec2 modify-instance-metadata-options \
  --instance-id "${EC2_ID}" \
  --http-endpoint enabled \
  --http-tokens required

To change an AMI so that instances launched from it have v2 enabled:

aws ec2 modify-image-attribute \
  --image-id "${AMI_ID}" \
  --imds-support v2.0

You will have to change how you retrieve instance metadata URIs [3].

v1:

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

v2:

TOKEN="$(curl -X PUT "http://169.254.169.254/latest/api/token" -H "X-aws-ec2-metadata-token-ttl-seconds: 21600")"

curl -s -H "X-aws-ec2-metadata-token: $TOKEN"  \

No comments: