Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save NitriKx/6271487 to your computer and use it in GitHub Desktop.
Save NitriKx/6271487 to your computer and use it in GitHub Desktop.
[New AWS CLI Tool] Create an aws-credential-file based on EC2 instance role using security token.
#!/bin/bash
ROLE=`curl http://169.254.169.254/latest/meta-data/iam/security-credentials/`
JSON=`curl http://169.254.169.254/latest/meta-data/iam/security-credentials/${ROLE}`
TOKEN=`echo ${JSON} | sed 's/\\\\\//\//g' | sed 's/[{}]//g' | awk -v k="text" '{n=split($0,a,","); for (i=1; i<=n; i++) print a[i]}' | sed 's/\"\:\"/\|/g' | sed 's/[\,]/ /g' | sed 's/\"//g' | grep -w 'Token' | cut -d":" -f2| sed -e 's/^ *//g' -e 's/ *$//g'`
# Get instance region and make it the default endpoint
EC2_AVAIL_ZONE=`curl -s http://169.254.169.254/latest/meta-data/placement/availability-zone`
AWS_INSTANCE_REGION="`echo \"$EC2_AVAIL_ZONE\" | sed -e 's:\([0-9][0-9]*\)[a-z]*\$:\\1:'`"
echo "[default]" > /tmp/aws_credentials
echo "aws_security_token=${TOKEN}" >> /tmp/aws_credentials
echo "region=${AWS_INSTANCE_REGION}" >> /tmp/aws_credentials
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment