Last active
February 12, 2021 22:10
-
-
Save mrapczynski/5cb1a5ad11bc52f15738b3b695f161df to your computer and use it in GitHub Desktop.
Zsh/Bash Function for Getting AWS Credentials from SSO
This file contains hidden or 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
# WHAT IS IT? | |
# | |
# After logging into an AWS organization that is SSO enabled using CLI v2, session credentials will be | |
# cached at $HOME/.aws/sso/cache. Most AWS tools do not know how to integrate directly with AWS SSO. This | |
# small function for Bash and Zsh gives you a quick shortcut to get temporary STS credentials | |
# and exports them as environment variables which your tools are likely to understand. Primary use case | |
# I wrote this for is using the Docker AWS ECR credential helper. I often toggle between different AWS | |
# organizations, and this function understands looking through the token cache for the correct one based | |
# the SSO start URL. | |
# | |
# HOW TO INSTALL | |
# | |
# Copy/paste the function below into your .zshrc or .bashrc file. Each new shell session will have the | |
# function ready to go. | |
# | |
# HOW TO USE | |
# | |
# > aws-sso-get-credentials profile-name-goes-here | |
function aws-sso-get-credentials { | |
aws_desired_profile="$1" | |
echo "Loading AWS profile $aws_desired_profile" | |
sso_start_url=`aws configure get sso_start_url --profile $aws_desired_profile` | |
sso_region=`aws configure get sso_region --profile $aws_desired_profile` | |
sso_account_id=`aws configure get sso_account_id --profile $aws_desired_profile` | |
sso_role_name=`aws configure get sso_role_name --profile $aws_desired_profile` | |
sso_access_token=`jq -c -r --slurp '.[]? | select(.startUrl == "'$sso_start_url'" and .region == "'$sso_region'") | .accessToken' $HOME/.aws/sso/cache/*.json` | |
echo "Fetching STS credentials from SSO service (environment=$sso_start_url, region=$sso_region, role=$sso_role_name)" | |
aws_role_credentials=`aws sso get-role-credentials --profile $aws_desired_profile --role-name $sso_role_name --account-id $sso_account_id --access-token $sso_access_token` | |
# Export the credentials as environment variables other tools can consume | |
export AWS_ACCESS_KEY_ID=`echo $aws_role_credentials | jq -r -s '.[].roleCredentials.accessKeyId'` | |
export AWS_SECRET_ACCESS_KEY=`echo $aws_role_credentials | jq -r -s '.[].roleCredentials.secretAccessKey'` | |
export AWS_SESSION_TOKEN=`echo $aws_role_credentials | jq -r -s '.[].roleCredentials.sessionToken'` | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment