Rapidly switch AWS CLI profiles
July 2nd, 2020
This simple bash/zsh function makes it easy to switch between AWS CLI user profiles in your terminal sessions.
I often find myself using the AWS CLI with multiple accounts and IAM users, and find switching between them using the --profile option tedious.
Here's a cute little shell function to make handling profiles easier, by setting the appropriate environment variable for all subsequent AWS CLI calls in the current terminal session.
When used with a profile name, it simply sets the AWS_PROFILE environment variable to the profile or your choice. It also allows you to quickly view and check the current profile's user details, in case your profile name isn't enough information to tell you what you need to know.
The code
function awsuser() {
if [ "$1" = "" ]; then
AWS_ACCOUNT_ALIAS=$(aws iam list-account-aliases --query "AccountAliases[0]" --output text)
USER_DETAILS=$(aws iam get-user --output json)
AWS_USER=$(echo $USER_DETAILS | jq -r .User.UserName)
AWS_ACCOUNT_ID=$(echo ${USER_DETAILS} | jq -r .User.Arn | sed -e 's/.*:://g' -e 's/:.*//g')
echo "(${AWS_PROFILE:-default}): ${AWS_ACCOUNT_ID}:${AWS_ACCOUNT_ALIAS} -> ${AWS_USER}"
elif [ "-l" = "$1" ]; then
AWS_SHARED_CREDENTIALS_FILE=${AWS_SHARED_CREDENTIALS_FILE:-${HOME}/.aws/credentials}
grep "\[" ${AWS_SHARED_CREDENTIALS_FILE}
else
export AWS_PROFILE=$1
fi
}
Using it
So let's say you've got ~/.aws/credentials
configured as follows:
[devaccount-admin]
aws_access_key_id = ......
aws_secret_access_key = ......
[devaccount-developer]
aws_access_key_id = ......
aws_secret_access_key = ......
[prodaccount-admin]
aws_access_key_id = ......
aws_secret_access_key = ......
[prodaccount-user]
aws_access_key_id = ......
aws_secret_access_key = ......
You can get a quick list of all your profiles:
$ awsuser -l
[devaccount-admin]
[devaccount-developer]
[prodaccount-admin]
[prodaccount-user]
Switch to a specific user profile:
$ awsuser devaccount-admin
Then run with no args to see the profile, account ID and alias, and user ID you're currently running with:
$ awsuser
(devaccount-admin): 123456789012:dmakovecdevaccount -> admin
$ aws iam get-user
{
"User": {
"Path": "/",
"UserName": "admin",
"UserId": "......",
"Arn": "arn:aws:iam::123456789012:user/admin",
"CreateDate": "2020-06-01T07:18:28+00:00",
"PasswordLastUsed": "2020-07-03T05:14:48+00:00"
}
}