Hello,
Do you have an Assume Role?
If YES and If you use AWS-related CLI tools in the switch roll destination environment, you will usually need to use the Assume Role.
I wrote a script about how to ease the task of assuming a role programmatically because it is even tedious to do that .
About scripts
The introduction has become long, but I will go into the main subject.
I would like to implement it and then post the operation image.
Preparation
First, prepare before writing the script.
Have fzf and Grep handy.
Regarding fzf, the installation method on various OS is described in the README.
$ brew install fzf
Script placement
Place the script below wherever you like.
If you need MFA of the script when deploying, change MFA Serial on the 3rd line to each value.
If you don’t need aws sts assume-role
it, delete it and change the argument.
In addition, the fourth line SOURCE_PROFILE
please write a profile of the AWS account that runs the Assume Role in.
_assumer
#!/bin/bash
SERIAL_NUMBER='arn:aws:iam::xxxxxxxxxxxx:mfa/xxxxxxxxxxxx'
SOURCE_PROFILE='xxxxxxxxxxxx'
DATE=`date +%s`
PROFILE=`grep -oP '\[profile *\K\w+' ~/.aws/config | fzf`
if [ "$PROFILE" = "" ]; then
return 1
fi
ROLE_ARN=`aws configure get role_arn --profile $PROFILE`
read -sp "Input MFA Code: " TOKEN_CODE
OUTPUT=`aws sts assume-role \
--role-arn ${ROLE_ARN} \
--serial-number ${SERIAL_NUMBER} \
--role-session-name ${DATE}-session \
--profile ${SOURCE_PROFILE} \
--duration-second 3600 \
--token-code ${TOKEN_CODE}
`
export AWS_ACCESS_KEY_ID=`echo $OUTPUT | jq -r .Credentials.AccessKeyId`
export AWS_SECRET_ACCESS_KEY=`echo $OUTPUT | jq -r .Credentials.SecretAccessKey`
export AWS_SESSION_TOKEN=`echo $OUTPUT | jq -r .Credentials.SessionToken`
echo ""
Alias setting
Set an alias for the script you just installed.
You can’t pass shell variables to the parent process if you just run the shell script.
So let’s use the source command to bridge shell variables nicely.
I’m using bash, so .bash_profile
I’ll set an alias like this:
.bash_profile
alias assume='. /path/to/_assumer'
Operation image
Sorry for the image but it works like this.assume
If you type, fzf will do a fuzzy search.

Then select the profile you want to use and the AWS CLI will call the Assume Role.
Insert a 6-digit token.

If it succeeds, it will end without displaying anything, so type any command you like.