Get MFA API credentials for AWS

Viewed 172

Let's say I have set up an IAM policy to enforce multi-factor authentication (MFA) for all AWS API requests (such as the one described here: https://stackoverflow.com/a/70792832/2800876). I can get and use temporary credentials via sts get-session-token with the following code:

# Get the serial number of your MFA device
aws --profile <PROFILE_NAME> iam list-mfa-devices --user-name <IAM_USER_NAME>

# Get temporary API keys that will pass MFA verification
aws --profile <PROFILE_NAME> sts get-session-token --serial-number <MFA_SERIAL_NUMBER> --token-code <MFA_TOKEN>

# Export the temporary credentials for use in subsequent calls
export AWS_ACCESS_KEY_ID=<KEY>
export AWS_SECRET_ACCESS_KEY=<SECRET>
export AWS_SESSION_TOKEN=<SESSION_TOKEN>

However, this code requires several steps and only works for the terminal window I do it in. How do I make this work with a single command that saves the credentials until they expire?

1 Answers

There is a command line tool called iam-mfa that will do this for you: https://github.com/zagaran/iam-mfa. (Disclaimer: I am the primary author of the tool.)

The key is to use named profiles. One profile (the source_profile) will hold the credentials that you use to call sts get-session-token. The other profile (the dest_profile) will be where you save the session token you get from sts, and is the profile you use to do all subsequent API calls.

You can install it with pip install iam-mfa.

You can then call it with:

iam-mfa <source_profile> <dest_profile> <iam_username>

When you run the script, it will prompt you for an MFA code.

Related