DEV Community

John Gakhokidze
John Gakhokidze

Posted on

Assuming role in AWS CLI with MFA authentication.

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:

  6. initial profile to use

  7. temp profile name - which will be your profile with MFA authentication

  8. role arn

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

  10. role profile name, which you can refer

  11. MFA arn

  12. current MFA token

Script

  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

MFA auth

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

MFA auth

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

Top comments (0)