Last active
July 18, 2019 19:58
-
-
Save bitroniq/8b038159bb251b174fff0317bfedace9 to your computer and use it in GitHub Desktop.
Get AWS IAM security credentials from instance metadata on a plain EC2 or docker container and writes them to i environment variables and .s3cfg (for s3cmd)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env sh | |
# First, we need to grab the name of the IAM role attached to the instance. | |
instance_profile=$(curl http://169.254.169.254/latest/meta-data/iam/security-credentials/) | |
# Alright, we’ve got the IAM role name, which we’ll now use to grab the access and secret access keys. | |
aws_access_key_id=$(curl http://169.254.169.254/latest/meta-data/iam/security-credentials/"${instance_profile}" | grep AccessKeyId | cut -d':' -f2 | sed 's/[^0-9A-Z]*//g') | |
aws_secret_access_key=$(curl http://169.254.169.254/latest/meta-data/iam/security-credentials/"${instance_profile}" | grep SecretAccessKey | cut -d':' -f2 | sed 's/[^0-9A-Za-z/+=]*//g') | |
aws_session_token=$(curl http://169.254.169.254/latest/meta-data/iam/security-credentials/"${instance_profile}" | grep Token | awk '{ print $3 }' | sed -e 's/^"//' -e 's/",//') | |
aws_security_token=$(curl http://169.254.169.254/latest/meta-data/iam/security-credentials/"${instance_profile}" | grep Token | awk '{ print $3 }' | sed -e 's/^"//' -e 's/",//') | |
# Now we have the keys. We can then export then to the environment and run our tests. | |
export AWS_ACCESS_KEY_ID=${aws_access_key_id} | |
export AWS_SECRET_ACCESS_KEY=${aws_secret_access_key} | |
export AWS_SESSION_TOKEN=${aws_session_token} | |
export AWS_SECURITY_TOKEN=${aws_security_token} | |
# Make directory if not exist | |
[ -d ~/.aws ] || mkdir -p ~/.aws | |
# Creating .aws files | |
cat << EOF > ~/.aws/config | |
[default] | |
region=us-east-1 | |
output=json | |
EOF | |
echo "[${instance_profile}]" > ~/.aws/credentials | |
echo AWS_ACCESS_KEY_ID="${AWS_ACCESS_KEY_ID}" >> ~/.aws/credentials | |
echo AWS_SECRET_ACCESS_KEY="${AWS_SECRET_ACCESS_KEY}" >> ~/.aws/credentials | |
echo AWS_SESSION_TOKEN="${AWS_SESSION_TOKEN}" >> ~/.aws/credentials | |
echo AWS_SECURITY_TOKEN="${AWS_SECURITY_TOKEN}" >> ~/.aws/credentials |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment