AWS Management — Assuming role in AWS CLI with MFA authentication.

John Gakhokidze
2 min readAug 6, 2020

Sometimes you need to assume role while working with aws cli, but role assuming condition is to be authenticated by MFA.

Here is script which makes it fun.
Script is available in my git repo

What we are doing here:

  1. We use normal profile to get session Token, with MFA authentication.
  2. We create temp profile for MFA authenticated session.
  3. We authenticated and assume desired role with that profile and add role profile to .aws/credentials file
  4. Then, we can start using it in any aws cli command with --profile argument
  5. What information we need:

a. initial profile to use

b. temp profile name — which will be your profile with MFA authentication

c. role session name (anything you like to name it)

d. role profile name, which you can refer

e. current MFA arn and token

  1. Now we are getting MFA authentication session object, and parsing it to extract:
  2. aws_access_key_id
  3. aws_secret_access_key
  4. aws_session_token

I intentionally left sed parse not optimized, for ease of understanding

Using temporary MFA authenticated profile we are assuming role, and getting role session authentication object, which we parse and extract data in step 2

after writing temporary role profile to .aws/credentials we can use it with --profile argument in aws cli

Originally published at on August 6, 2020.