Skip to content

Instantly share code, notes, and snippets.

@MatteoGioioso
Last active April 16, 2023 05:57
Show Gist options
  • Save MatteoGioioso/ec5f30a4996a381b10f81f1e748a07fe to your computer and use it in GitHub Desktop.
Save MatteoGioioso/ec5f30a4996a381b10f81f1e748a07fe to your computer and use it in GitHub Desktop.
Export AWS SSO credentials
#!/bin/bash
echo "unsetting previous aws credentials..."
unset AWS_ACCESS_KEY_ID
unset AWS_SECRET_ACCESS_KEY
unset AWS_SESSION_TOKEN
aws sso login &&
aws sts get-caller-identity > /dev/null && # this refresh the cache
echo "sourcing aws credentials"
JSON_BASEPATH="${HOME}/.aws/cli/cache" # the cache folder contains the cached credentials from the sessions
json_file=$(ls -tr "${JSON_BASEPATH}" | tail -n1) # list in reverse cronological order and tail the last line
export AWS_ACCESS_KEY_ID=$(cat ${JSON_BASEPATH}/${json_file} | jq -r '.Credentials.AccessKeyId')
export AWS_SECRET_ACCESS_KEY=$(cat ${JSON_BASEPATH}/${json_file} | jq -r '.Credentials.SecretAccessKey')
export AWS_SESSION_TOKEN=$(cat ${JSON_BASEPATH}/${json_file} | jq -r '.Credentials.SessionToken')
echo "done!"
@MatteoGioioso
Copy link
Author

MatteoGioioso commented Apr 16, 2023

  • To login into a specific profile, specify it via environmental variable AWS_PROFILE=myprofile
  • You can wrap this into a function in your bash profile or .zshrc, ex:
     aws-sso-login(){
       // this gist code
    }
    

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