Skip to content

Instantly share code, notes, and snippets.

@alfredocambera
Last active May 10, 2021 23:01
Show Gist options
  • Save alfredocambera/ed89d53ad4590fa944f7cde41f746200 to your computer and use it in GitHub Desktop.
Save alfredocambera/ed89d53ad4590fa944f7cde41f746200 to your computer and use it in GitHub Desktop.
How to get instance role creddentials using assigned EC2's IAM role using IMDSv2
#!/usr/bin/env bash
TOKEN_TTL=900 # 15 minutes
ROLE="$(curl -s http://169.254.169.254/latest/meta-data/iam/security-credentials/)"
TOKEN="$(curl -s -X PUT "http://169.254.169.254/latest/api/token" -H "X-aws-ec2-metadata-token-ttl-seconds: ${TOKEN_TTL}")"
CREDS="$(curl -s -H "X-aws-ec2-metadata-token: ${TOKEN}" "http://169.254.169.254/latest/meta-data/iam/security-credentials/${ROLE}")"
REGION=$(curl -s http://169.254.169.254/latest/dynamic/instance-identity/document | jq -r .region)
AWS_ACCESS_KEY_ID="$(echo "${CREDS}" | jq -r .AccessKeyId)"
AWS_SECRET_ACCESS_KEY="$(echo "${CREDS}" | jq -r .SecretAccessKey)"
AWS_SESSION_TOKEN="$(echo "${CREDS}" | jq -r .Token)"
AWS_REGION="${REGION}"
export AWS_ACCESS_KEY_ID
export AWS_SECRET_ACCESS_KEY
export AWS_SESSION_TOKEN
export AWS_REGION
aws s3 ls # replace with a command you are allowed to run
#--------------------------------------------------------------------------------------------------
# References
# - https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html#instance-metadata-security-credentials
#--------------------------------------------------------------------------------------------------
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment