Skip to content

Instantly share code, notes, and snippets.

@walmsles

walmsles/awsenv Secret

Created March 9, 2021 10:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save walmsles/e9f837bfbf567ffd29e99ae7f6612988 to your computer and use it in GitHub Desktop.
Save walmsles/e9f837bfbf567ffd29e99ae7f6612988 to your computer and use it in GitHub Desktop.
#!/bin/bash
profile=$1
profile_dir=$HOME/.aws/profiles
mfa_token=$2
if [[ -z "${profile}" || -z "${mfa_token}" ]]
then
echo "usage: awsenv <profile> <mfa_code>"
elif [[ ! -f "${profile_dir}/${profile}" ]]
then
echo "AWS Profile [${profile}] not found in [${profile_dir}]"
else
unset AWS_ACCESS_KEY_ID
unset AWS_SECRET_ACCESS_KEY
unset AWS_DEFAULT_REGION
unset AWS_ARN_MFA
unset AWS_SESSION_TOKEN
source $profile_dir/$profile
if [[ "${mfa_token}" ]]
then
if [[ -z "AWS_ARN_MFA" ]]
then
echo "need to set AWS_ARN_MFA environment variable with ARN of mfa device in AWS"
echo "unable to continue"
else
token_data=$(aws sts get-session-token --serial-number $AWS_ARN_MFA --token-code $mfa_token)
if [[ $? == 0 ]]
then
awskey=$(echo $token_data | jq '.Credentials.AccessKeyId' | sed -E 's/^\"(.*)\"$/\1/g')
awssecret=$(echo $token_data | jq '.Credentials.SecretAccessKey' | sed -E 's/^\"(.*)\"$/\1/g')
awssession=$(echo $token_data | jq '.Credentials.SessionToken' | sed -E 's/^\"(.*)\"$/\1/g')
export AWS_ACCESS_KEY_ID=${awskey}
export AWS_SECRET_ACCESS_KEY=${awssecret}
export AWS_SESSION_TOKEN=${awssession}
fi
fi
fi
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment