Skip to content

Instantly share code, notes, and snippets.

@shdobxr
Forked from fgassert/ec2-get-security-credentials
Created September 13, 2018 19:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shdobxr/5864e1a40b38a92ca983312fb74487c5 to your computer and use it in GitHub Desktop.
Save shdobxr/5864e1a40b38a92ca983312fb74487c5 to your computer and use it in GitHub Desktop.
gets iam security credentials from instance metadata and writes them to awscli environment variables and .s3cfg (for s3cmd)
#!/bin/bash
# gets iam security credentials from instance metadata and writes them to
# awscli environment variables and .s3cfg (for s3cmd)
# Usage: ec2-get-security-credentials ROLENAME DEFAULT_REGION
# ROLE=$1
# DEFAULT_REGION=$2
if [ -n "$1" ] ; then
# get jq for json queries
curl -O http://stedolan.github.io/jq/download/linux64/jq
chmod +x jq
# get security credentials from instance metadata
curl -o security-credentials.json http://169.254.169.254/latest/meta-data/iam/security-credentials/$1/
export AWS_ACCESS_KEY_ID=$(cat security-credentials.json | ./jq -r '.AccessKeyId')
export AWS_SECRET_ACCESS_KEY=$(cat security-credentials.json | ./jq -r '.SecretAccessKey')
export AWS_SECURITY_TOKEN=$(cat security-credentials.json | ./jq -r '.Token')
# Write to .s3cfg
echo '[default]' > .awscli
echo aws_access_key_id=$AWS_ACCESS_KEY_ID >> .awscli
echo aws_secret_access_key=$AWS_SECRET_ACCESS_KEY >> .awscli
echo aws_security_token=$AWS_SECURITY_TOKEN >> .awscli
# Write to .s3cfg
echo '[default]' > .s3cfg
echo access_key=$AWS_ACCESS_KEY_ID >> .s3cfg
echo secret_key=$AWS_SECRET_ACCESS_KEY >> .s3cfg
echo access_token=$AWS_SECURITY_TOKEN >> .s3cfg
if [ -n "$2" ] ; then
export AWS_DEFAULT_REGION=$2
echo region=$2 >> .awscli
fi
else
echo 'ERR: No role name specificed'
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment