Securing your AWS IAM user with multi factor authentication (MFA) is a good idea. However, when working on the command line interface (CLI), the need to enter changing token codes creates some overhead. This article shows how to use MFA in the CLI.
Enabling MFA
This documentation shows how to enable MFA. With these settings, logins to the web console via the browser will only work with a code from your MFA device.
To also force IAM users to having to enter an MFA token code when using the CLI, set the IAM policy as shown here.
With this setup, any command given to the AWS CLI will fail without a proper token code:
Requesting and Setting Credentials Manually
Here is how to get a token and use it in every request. This process is also shown here on YouTube.
First, find the amazon resource name (ARN) of your MFA device. Go to the user table in IAM service and select your user. The tab “Security credentials” shows the ARN at “Assigned MFA device”.
With that, a token can be requested from the Security Token Service (STS), using one of the codes from your MFA device:
To make following commands in the AWS CLI use this token, it can be exported in the environment variables like this:
The second script, aws-set-mfa-access-token.sh, requests new credentials from the STS as shown above and sets them in the environment variables:
Both scripts come with a help page and some user friendliness such as input validation and informative output. They can be downloaded at this GitHub repository.
Note: AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY and AWS_SESSION_TOKEN could also be added to the credentials file stored in the .aws folder. However, Amazon recommends using the environment variables. Also, there is no easy way adding the values to the credentials file via the AWS CLI.