Last active
September 6, 2019 05:08
-
-
Save bdargan/d2072830802d33ec0d42332e7f61d845 to your computer and use it in GitHub Desktop.
aws cli - assume role with MFA with cross-account support
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 zsh | |
#echo "This script depends on correctly configured aws credentials file. \n1. profile, \n2. dest_profile, contains role_arn in dest_account and refers creds to the source_profile, \n3. source_profile contains sts temporary credentials" | |
echo "1. Authenticate with current AWS_PROFILE (${AWS_PROFILE}) - please provide your account Id and iam username and your MFA token" | |
echo "2. Assume role as configured in ~/aws/.credentials#${DEST_PROFILE=DEST_PFOFILE}" | |
if [ -z `which jq` ]; then | |
echo "ERROR: required command:'jq' command line JSON processor - https://github.com/stedolan/jq" | |
exit 1 | |
fi | |
if [ -z "$SOURCE_ACCOUNT_ID" ]; then | |
echo -n 'SOURCE_ACCOUNT_ID: ' | |
read SOURCE_ACCOUNT_ID; | |
fi | |
if [ -z "$IAM_USERNAME" ]; then | |
echo -n 'IAM_USERNAME: ' | |
read IAM_USERNAME; | |
fi | |
if [ -z "$AWS_PROFILE" ]; then | |
echo -n 'AWS_PROFILE: ' | |
read PROFILE; | |
fi | |
if [ -z "$DEST_PROFILE" ]; then | |
echo -n 'DEST_PROFILE: ' | |
read DEST_PROFILE; | |
fi | |
if [ -z "$TOKEN" ]; then | |
echo -n 'Token: ' | |
read TOKEN; | |
fi | |
TMP_PROFILE="${DEST_PROFILE}-tmp" | |
echo "aws sts get-session-token --serial-number arn:aws:iam::${SOURCE_ACCOUNT_ID}:mfa/${IAM_USERNAME} --token-code $TOKEN --profile $AWS_PROFILE" | |
STS_CREDS=`aws sts get-session-token --serial-number arn:aws:iam::${SOURCE_ACCOUNT_ID}:mfa/${IAM_USERNAME} --token-code $TOKEN --profile $AWS_PROFILE` | |
aws configure set "profile.$TMP_PROFILE.aws_access_key_id" `echo $STS_CREDS|jq -r .Credentials.AccessKeyId` | |
aws configure set "profile.$TMP_PROFILE.aws_secret_access_key" `echo $STS_CREDS|jq -r .Credentials.SecretAccessKey` | |
aws configure set "profile.$TMP_PROFILE.aws_session_token" `echo $STS_CREDS|jq -r .Credentials.SessionToken` | |
unset STS_CREDS | |
unset TOKEN | |
aws sts get-caller-identity --profile $DEST_PROFILE | |
echo "export AWS_PROFILE=${DEST_PROFILE}; # if you forgot to run this in current shell" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment