-
-
Save kkumler/75ba5893a5387185ec23 to your computer and use it in GitHub Desktop.
Assume an IAM role. An interesting way of doing IAM roles is to give the instance permissions to assume another role, but no actual permissions by default. I got this idea while setting up security monkey: http://securitymonkey.readthedocs.org/en/latest/quickstart1.html#setup-iam-roles.
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
#!/bin/bash | |
# | |
# Assume the given role, and print out a set of environment variables | |
# for use with aws cli. | |
# | |
# To use: | |
# | |
# $ eval $(./iam-assume-role.sh) | |
# | |
set -e | |
# Clear out existing AWS session environment, or the awscli call will fail | |
unset AWS_ACCESS_KEY_ID AWS_SECRET_ACCESS_KEY AWS_SESSION_TOKEN AWS_SECURITY_TOKEN | |
# Old ec2 tools use other env vars | |
unset AWS_ACCESS_KEY AWS_SECRET_KEY AWS_DELEGATION_TOKEN | |
ROLE="${1:-SecurityMonkey}" | |
ACCOUNT="${2:-123456789}" | |
DURATION="${3:-900}" | |
NAME="${4:-$LOGNAME@$(hostname -s)}" | |
if [[ $ROLE == arn* ]] ; then | |
ROLE_ARN="${ROLE}" | |
else | |
if [ "${ACCOUNT}" == "123456789" ]; then | |
echo "ARN or account & role required!" 1>&2 | |
exit 1 | |
fi | |
ROLE_ARN="arn:aws:iam::${ACCOUNT}:role/${ROLE}" | |
fi | |
# KST=access*K*ey, *S*ecretkey, session*T*oken | |
KST=($(aws sts assume-role --role-arn "${ROLE_ARN}" \ | |
--role-session-name "${NAME}" \ | |
--duration-seconds "${DURATION}" \ | |
--query '[Credentials.AccessKeyId,Credentials.SecretAccessKey,Credentials.SessionToken]' \ | |
--output text)) | |
echo 'export AWS_DEFAULT_REGION=${AWS_DEFAULT_REGION:-us-east-1}' | |
echo "export AWS_ACCESS_KEY_ID='${KST[0]}'" | |
echo "export AWS_SECRET_ACCESS_KEY='${KST[1]}'" | |
echo "export AWS_SESSION_TOKEN='${KST[2]}'" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment