How to add Assume role in VSCode to get temporary access to AWS?
Hi, this is Charu from Classmethod.
Before moving on to the topic, I will tell you what I used to do to connect to AWS. I used to type aws configure in the terminal and then enter my access key and secret access key. This method is totally unsafe to perform. You can easily put your credentials at risk. To avoid this, we will be using assume role technique. It uses AWS CLI to obtain temporary credentials which can be used for authentication while connecting to AWS.
Let's get Started:
To get started, we will first look into our config and credentials file. The data in these files are necessary for the assume role command.
Type cat ~/.aws/config
and check the content. It should look something like this,
[default]
region=ap-northeast-1
output=json
[profile YOUR-PROFILE-NAME]
region = ap-northeast-1
mfa_serial = arn:aws:iam::xxxxxxxxxxxx:mfa/abc
role_arn = arn:aws:iam::yyyyyyyyyyyy:role/abc
source_profile = default
You can go to IAM > Roles, select your role and click on the Edit button to set the session duration.
You can find your mfa_serial(root account) and role_arn(switch role) from the AWS console respectively as shown below,
Let's check our credentials file next. Type cat ~/.aws/credentials
in the terminal. It should look something like this,
[default]
aws_access_key_id = xxxxxxxxxx
aws_secret_access_key = yyyyyyyyyy
Now, the command to enable assume role is,
AWS_PROFILE="PROFILE_NAME"
tokenCode="TOKEN_CODE_NUMBER"
AWS_STS_CREDENTIALS=`aws sts assume-role \
--profile default \
--role-arn $(aws configure get ${AWS_PROFILE}.role_arn) \
--role-session-name ${AWS_PROFILE}-session \
--serial-number $(aws configure get ${AWS_PROFILE}.mfa_serial) \
--duration-seconds $((60*60*12)) \
--token-code ${tokenCode}`
export AWS_ACCESS_KEY_ID=`echo "${AWS_STS_CREDENTIALS}" | jq -r '.Credentials.AccessKeyId'`
export AWS_SECRET_ACCESS_KEY=`echo "${AWS_STS_CREDENTIALS}" | jq -r '.Credentials.SecretAccessKey'`
export AWS_SESSION_TOKEN=`echo "${AWS_STS_CREDENTIALS}" | jq -r '.Credentials.SessionToken'`
unset AWS_PROFILE
Enter the PROFILE_NAME and the TOKEN_CODE_NUMBER which is your MFA code(check your MFA device). The token code is necessary if the role you are assuming requires MFA.
Let's break down the command and try to understand it,
aws configure get ${AWS_PROFILE}.role_arn
command. aws configure get ${AWS_PROFILE}.mfa_serial
command.If you get an error saying jq not found, you can install it by typing,
brew install jq
Once this command this executed, you will be able to use the assume role.
Thank you for reading!
Happy Learning:)