DEV Community

Cover image for Use MFA on the CLI and execute awscli commands securely
An Rodriguez
An Rodriguez

Posted on • Updated on • Originally published at Medium

Use MFA on the CLI and execute awscli commands securely

To enhance security, you can enable multi-factor authentication (MFA) also for issuing CLI commands.

You can configure your MFA device by going to the IAM console, searching a user and follow these arrows:

Configure your virtual MFA device

Configure your virtual MFA device

IAM policy example

For example, you configure a Trust Policy as copied below. Notice the Condition to have MultiFactorAuthPresent. This way, in order for a user to assume a role in the CLI, the user must have an MFA token.

This condition can be applied to any Action of any IAM policy.

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "",
      "Effect": "Allow",
      "Principal": {
        "AWS": [
          "arn:aws:iam::nnnnnnnnnnnn:user/user.name"
        ]
      },
      "Action": "sts:AssumeRole",
      "Condition": {
        "Bool": {
          "aws:MultiFactorAuthPresent": "true"
        }
      }
    }
  ]
}
Enter fullscreen mode Exit fullscreen mode

Manually using the CLI to obtain the temporary session tokens and setting them up as environment variables can be a hassle. I came up with this quick script to automate the job.

In the following script, you only have to replace YOUR_MFA_ARN with the ARN of the MFA device you have configured in your security settings in your AWS IAM user.

Then you can either source or execute the script.

Full article here

Here's the bash script aws-mfa-cli.sh:

Top comments (3)

Collapse
 
ronaldmartens profile image
RonaldMartens

Hi Mich,

Thanks for your script!
I changed 'YOUR_MFA_ARN' with my actual ARN, but when I run it the script still ends with "Please specify the MFA_DEVICE_ARN".
I uncommented the part:
if [ MFA_DEVICE_ARN=YOUR_MFA_ARN ]; then
echo "Please specify the MFA_DEVICE_ARN"
exit 1
fi
and then it worked fine. Do I have to put my ARN between some kind of punctuation marks?
I want to use it for the other sys admins.

Thanks,
Ronald

Collapse
 
ronaldmartens profile image
RonaldMartens

You have to put [ MFA_DEVICE_ARN=YOUR_MFA_ARN ] like [ MFA_DEVICE_ARN = YOUR_MFA_ARN ]
spaces between the inputs...

Collapse
 
samesame80 profile image
4speculators

We just published a video how to do CLI with MFA youtu.be/y6jTIuz-oMc