Skip to content

Instantly share code, notes, and snippets.

@skehlet
Created November 9, 2017 19:54
Show Gist options
  • Save skehlet/c3daebdf63cc4ba6cc6c3ebbfd9d98bd to your computer and use it in GitHub Desktop.
Save skehlet/c3daebdf63cc4ba6cc6c3ebbfd9d98bd to your computer and use it in GitHub Desktop.
#!/bin/bash
set -e
unset AWS_ACCESS_KEY_ID
unset AWS_SECRET_ACCESS_KEY
unset AWS_SESSION_TOKEN
unset AWS_DEFAULT_REGION
unset AWS_DEFAULT_OUTPUT
unset AWS_PROFILE
unset AWS_CA_BUNDLE
unset AWS_SHARED_CREDENTIALS_FILE
unset AWS_CONFIG_FILE
# CHANGE THESE AS NEEDED
export AWS_PROFILE=<your-hub-profile-in-~/.aws/config>
export AWS_DEFAULT_REGION=us-west-2
MFA_ARN=<your-mfa-arn>
ROLE_ARN=<your-role-arn>
# NO FURTHER CHANGES
TMPFILE=$(mktemp)
trap 'rm -f $TMPFILE' EXIT
read -p "MFA code: " code
aws sts get-session-token --serial-number $MFA_ARN --token-code "$code" > $TMPFILE
AWS_ACCESS_KEY_ID=$(jq -r '.Credentials.AccessKeyId' < $TMPFILE)
AWS_SECRET_ACCESS_KEY=$(jq -r '.Credentials.SecretAccessKey' < $TMPFILE)
AWS_SESSION_TOKEN=$(jq -r '.Credentials.SessionToken' < $TMPFILE)
export AWS_ACCESS_KEY_ID AWS_SECRET_ACCESS_KEY AWS_SESSION_TOKEN
aws sts assume-role --role-arn $ROLE_ARN --role-session-name $(date +%s) > $TMPFILE
AWS_ACCESS_KEY_ID=$(jq -r '.Credentials.AccessKeyId' < $TMPFILE)
AWS_SECRET_ACCESS_KEY=$(jq -r '.Credentials.SecretAccessKey' < $TMPFILE)
AWS_SESSION_TOKEN=$(jq -r '.Credentials.SessionToken' < $TMPFILE)
echo unset AWS_ACCESS_KEY_ID\;
echo unset AWS_SECRET_ACCESS_KEY\;
echo unset AWS_SESSION_TOKEN\;
echo unset AWS_DEFAULT_REGION\;
echo unset AWS_DEFAULT_OUTPUT\;
echo unset AWS_PROFILE\;
echo unset AWS_CA_BUNDLE\;
echo unset AWS_SHARED_CREDENTIALS_FILE\;
echo unset AWS_CONFIG_FILE\;
echo export AWS_ACCESS_KEY_ID=\"$AWS_ACCESS_KEY_ID\"\;
echo export AWS_SECRET_ACCESS_KEY=\"$AWS_SECRET_ACCESS_KEY\"\;
echo export AWS_SESSION_TOKEN=\"$AWS_SESSION_TOKEN\"\;
echo export AWS_DEFAULT_REGION=\"$AWS_DEFAULT_REGION\"\;
role=$(aws sts get-caller-identity | jq -r .Arn)
echo "echo Your role is now: $role"\;
@skehlet
Copy link
Author

skehlet commented Nov 9, 2017

Then in your ~/.aws/config:

[profile your-hub-profile]
region = us-west-2

Then in your ~/.aws/credentials:

[your-hub-profile]
aws_access_key_id = <your-access-key-id>
aws_secret_access_key = <your-secret-access-key>

Then to invoke it:

eval $(./my-assume-role )

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment