Skip to content

Instantly share code, notes, and snippets.

@slachiewicz
Forked from atheiman/metadata.sh
Created August 29, 2021 17:53
Show Gist options
  • Save slachiewicz/b2d024fe1468f758e1affa43461a38d5 to your computer and use it in GitHub Desktop.
Save slachiewicz/b2d024fe1468f758e1affa43461a38d5 to your computer and use it in GitHub Desktop.
EC2 Metadata API basics
# https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-instance-metadata.html
METADATA_TOKEN="$(curl -s -X PUT 'http://169.254.169.254/latest/api/token' -H 'X-aws-ec2-metadata-token-ttl-seconds: 21600')"
AVAILABILITY_ZONE="$(curl -s -H "X-aws-ec2-metadata-token: $METADATA_TOKEN" http://169.254.169.254/latest/meta-data/placement/availability-zone)"
export AWS_REGION="$(echo "$AVAILABILITY_ZONE" | rev | cut -c 2- | rev)"
export AWS_DEFAULT_REGION="$AWS_REGION"
export INSTANCE_ID="$(curl -s -H "X-aws-ec2-metadata-token: $METADATA_TOKEN" http://169.254.169.254/latest/meta-data/instance-id)"
# Instance identity documents is another very useful interface with many key value pairs in json format
# https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-identity-documents.html
curl -s -H "X-aws-ec2-metadata-token: $METADATA_TOKEN" http://169.254.169.254/latest/dynamic/instance-identity/document
# {
# "accountId" : "111111111111",
# "architecture" : "x86_64",
# "availabilityZone" : "us-east-1a",
# ...
# "imageId" : "ami-0123456789",
# "instanceType" : "t2.small",
# ...
# "pendingTime" : "2021-08-04T16:20:26Z",
# "privateIp" : "10.0.0.1",
# ...
# "region" : "us-east-1",
# "version" : "2017-09-30"
# }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment