Skip to content

Instantly share code, notes, and snippets.

@dukejones
Forked from gene1wood/aws_assume_role
Last active November 3, 2017 16:33
Show Gist options
  • Save dukejones/36128decdb1e003ac5d77f5c4523f1f5 to your computer and use it in GitHub Desktop.
Save dukejones/36128decdb1e003ac5d77f5c4523f1f5 to your computer and use it in GitHub Desktop.
Workaround AWS CLI lack of support for IAM assume-role
#!/bin/bash
set -e
usage () {
cat <<DOCUMENTATIONXX
Usage : $0 PROFILE_NAME COMMAND
This tool will take a named profile from your ~/.aws/credentials with only
a "role_arn = " line and no source profile, get temporary credentials for
the profile, and execute the rest of the parameters as a command with the
credentials set as environment variables.
Examples
$0 production aws ec2 describe-instances --region=us-west-1
DOCUMENTATIONXX
}
if [ "$1" == "-h" -o "$1" == "--help" -o "$1" == "" ]; then
usage
exit 1
fi
source_profile_name=$1
role_arn=$(cat $HOME/.aws/credentials | grep -A 1 "\[$source_profile_name\]" | tail -n 1 | sed 's/role_arn = //')
session_name="${USER}-`hostname`-`date +%Y%m%d`"
sts=( $(
aws sts assume-role \
--role-arn "$role_arn" \
--role-session-name "$session_name" \
--query 'Credentials.[AccessKeyId,SecretAccessKey,SessionToken]' \
--output text
) )
AWS_ACCESS_KEY_ID=${sts[0]} AWS_SECRET_ACCESS_KEY=${sts[1]} AWS_SESSION_TOKEN=${sts[2]} ${@:2}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment