Skip to content

Instantly share code, notes, and snippets.

@pwillis-els
Created September 30, 2020 20:35
Show Gist options
  • Save pwillis-els/0b715a3297264ce0b1ed65183fe4b1b6 to your computer and use it in GitHub Desktop.
Save pwillis-els/0b715a3297264ce0b1ed65183fe4b1b6 to your computer and use it in GitHub Desktop.
Retrieve AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, and AWS_SESSION_TOKEN from EC2 Instance Metadata
#!/bin/sh
set -eu
function json_v () { python -c 'import sys,json;j=json.load(sys.stdin); a=sys.argv[1:]; print("\n".join([j[k] for k in a]))' "$@" ; }
function _ec2_credentials () {
JSON=`curl -s http://169.254.169.254/latest/meta-data/identity-credentials/ec2/security-credentials/ec2-instance`
if [ -n "$JSON" ] ; then
AWS_ACCESS_KEY_ID=`printf "%s" "$JSON" | json_v AccessKeyId`
AWS_SECRET_ACCESS_KEY=`printf "%s" "$JSON" | json_v SecretAccessKey`
AWS_SESSION_TOKEN=`printf "%s" "$JSON" | json_v Token`
export AWS_ACCESS_KEY_ID AWS_SECRET_ACCESS_KEY AWS_SESSION_TOKEN
return 0
fi
return 1
}
_ec2_credentials
# If not sourced into a script ($0 = "-bash"), print values
if [ ! "${0:0:1}" = "-" ] ; then
printf "AWS_ACCESS_KEY_ID=%s\n" $AWS_ACCESS_KEY_ID
printf "AWS_SECRET_ACCESS_KEY=%s\n" $AWS_ACCESS_KEY_ID
printf "AWS_SESSION_TOKEN=%s\n" $AWS_ACCESS_KEY_ID
fi
# If command-line arguments were specified, execute them
if [ $# -gt 0 ] ; then
exec "$@"
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment