Skip to content

Instantly share code, notes, and snippets.

@caiusb
Last active May 5, 2023 05:42
Show Gist options
  • Save caiusb/8289d669ca374744cc00701b67ee3bcf to your computer and use it in GitHub Desktop.
Save caiusb/8289d669ca374744cc00701b67ee3bcf to your computer and use it in GitHub Desktop.
AWS Utils
# used in ~/.profile to make life easier when working with AWS services
# To assume a role run `assume <role-arn> <ext-id>`. The <ext-id> is optional and will default to `$USER`.
# To un-assume, run `unassume`.
# Role can be assumed sequentially, and credentials are "stacked". `unassume` will move you down that stack.
alias awswho='aws sts get-caller-identity'
alias assume='assume-role'
alias unassume='unassume-role'
export aws_access_key_arr=()
export aws_secret_key_arr=()
export aws_session_token_arr=()
export aws_security_token_arr=()
function assume-role() {
role=$1
extid=$2
response=$(aws sts assume-role --role-arn $role --role-session-name $USER --external-id ${extid:-$USER})
if [[ $? -ne 0 ]]; then
echo "Could not assume role"
return
fi
aws_access_key_arr=($AWS_ACCESS_KEY_ID "${aws_access_key_arr[@]}")
aws_secret_key_arr=($AWS_SECRET_ACCESS_KEY "${aws_secret_key_arr[@]}")
aws_session_token_arr=(${AWS_SESSION_TOKEN:-X} "${aws_session_token_arr[@]}")
aws_security_token_arr=(${AWS_SECURITY_TOKEN:-X} "${aws_security_token_arr[@]}")
export AWS_ACCESS_KEY_ID=$(echo $response | jq -r .Credentials.AccessKeyId)
export AWS_SECRET_ACCESS_KEY=$(echo $response | jq -r .Credentials.SecretAccessKey)
export AWS_SESSION_TOKEN=$(echo $response | jq -r .Credentials.SessionToken)
unset AWS_SECURITY_TOKEN
aws sts get-caller-identity
}
function unassume-role() {
if [[ ${aws_access_key_arr[0]} = '' ]]; then
echo "ERROR: No role to un-assume"
return 1
else
export AWS_ACCESS_KEY_ID=${aws_access_key_arr[0]}
export AWS_SECRET_ACCESS_KEY=${aws_secret_key_arr[0]}
export aws_access_key_arr=${aws_access_key_arr[@]:1}
export aws_secret_key_arr=${aws_secret_key_arr[@]:1}
if [[ ${aws_session_token_arr[0]} = 'X' ]]; then
unset AWS_SESSION_TOKEN
else
export AWS_SESSION_TOKEN=${aws_session_token_arr[0]}
export aws_session_token_arr=${aws_session_token_arr[@]:1}
fi
if [[ ${aws_security_token_arr[0]} = 'X' ]]; then
unset AWS_SECURITY_TOKEN
else
export AWS_SECURITY_TOKEN=${aws_security_token_arr[0]}
export aws_security_token_arr=${aws_security_token_arr[@]:1}
fi
fi
aws sts get-caller-identity
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment