Skip to content

Instantly share code, notes, and snippets.

@kxalex
Created March 18, 2021 06:05
Show Gist options
  • Save kxalex/29171479fcc66b5a2b20826ff61f0627 to your computer and use it in GitHub Desktop.
Save kxalex/29171479fcc66b5a2b20826ff61f0627 to your computer and use it in GitHub Desktop.
AWS create session token and save it to MFA profile
function aws-login() {
# set -x
# usage: aws-login token-code [aws-profile]
# token-code - a code from Authenticator
# aws-profile - session token will be created for this profile, if none supplied default or AWS_PROFILE will be used
local pkg=aws-login
local token_code=$1
if [[ ! $token_code ]]; then
echo "$pkg: missing required argument MFA_TOKEN" 1>&2
return 1
fi
local profile=$2
if [[ ! $profile ]]; then
profile=$AWS_PROFILE
fi
echo "AWS profile: $profile"
unset AWS_ACCESS_KEY_ID AWS_SECRET_ACCESS_KEY AWS_SESSION_TOKEN
local mfa_arn=$(aws --profile $profile iam get-user --user-name oshurubura | jq -r '.User.Arn' | sed 's/user/mfa/g')
echo "MFA Arn: $mfa_arn"
local rv creds_json
creds_json=$(aws --profile $profile --output json sts get-session-token --serial-number "$mfa_arn" --token-code $token_code)
rv="$?"
if [[ $rv -ne 0 || ! $creds_json ]]; then
echo "$pkg: failed to get credentials for '$mfa_arn': $creds_json" 1>&2
return "$rv"
fi
AWS_ACCESS_KEY_ID="$(echo $creds_json | jq -r '.Credentials.AccessKeyId')"
AWS_SECRET_ACCESS_KEY="$(echo $creds_json | jq -r '.Credentials.SecretAccessKey')"
AWS_SESSION_TOKEN="$(echo $creds_json | jq -r '.Credentials.SessionToken')"
echo "Updating mfa profile"
aws configure set aws_access_key_id "$AWS_ACCESS_KEY_ID" --profile mfa
aws configure set aws_secret_access_key "$AWS_SECRET_ACCESS_KEY" --profile mfa
aws configure set aws_session_token "$AWS_SESSION_TOKEN" --profile mfa
export AWS_PROFILE=mfa
#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"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment