Skip to content

Instantly share code, notes, and snippets.

@chrisdlangton
Last active May 17, 2020 04:16
Show Gist options
  • Save chrisdlangton/48d96c9084b4e07f8cda041f936d2454 to your computer and use it in GitHub Desktop.
Save chrisdlangton/48d96c9084b4e07f8cda041f936d2454 to your computer and use it in GitHub Desktop.
Use the temporary AWS security credentials created by STS assume-role rotated hourly
#!/usr/bin/env sh
if [ -z "$(which aws)" ]; then
echo "aws command not callable"
exit 1
fi
if [ -z "$(which python)" ]; then
echo "python command not found"
exit 1
fi
iam_role=$1
if [ -z "${iam_role}" ]; then
echo "missing argument: please supply an argument for iam_role"
exit 1
fi
session_name=$2
if [ -z "${session_name}" ]; then
session_name="$1-session"
fi
accountId=$(aws sts get-caller-identity --output text --query 'Account')
if [ -z "${accountId}" ]; then
accountId=$(curl -s http://instance-data/latest/dynamic/instance-identity/document/ | \
python -c "import sys, json; print(json.load(sys.stdin)['accountId'])")
if [ -z ${accountId} ]; then
echo "could not derive the account id or call the ec2 instance-data endpoint"
exit 1
fi
fi
role_output=$(aws sts assume-role --role-arn arn:aws:iam::${accountId}:role/${iam_role} --role-session-name ${session_name} --duration-seconds 3600)
export AWS_ACCESS_KEY_ID=$(echo $role_output | \
python -c "import sys, json; print(json.load(sys.stdin)['Credentials']['AccessKeyId'])")
export AWS_SECRET_ACCESS_KEY=$(echo $role_output | \
python -c "import sys, json; print(json.load(sys.stdin)['Credentials']['SecretAccessKey'])")
export AWS_SESSION_TOKEN=$(echo $role_output | \
python -c "import sys, json; print(json.load(sys.stdin)['Credentials']['SessionToken'])")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment