DEV Community

Rafaf Tahsin
Rafaf Tahsin

Posted on • Edited on

How to enforce MFA in AWS - Part II - Using `aws` CLI and terraform with MFA

Part I => How to enforce MFA in AWS CLI - Part I

Here in Part II we will discuss how to access aws using MFA

aws cli

1. Use aws configure --profile mfa_user to configure mfa user in aws cli. Get the user credentials from terraform outputs. Sensitive outputs can be retrieved with terraform output <sensitive_output_data>. After configuration your ~/.aws/credentials should contains this

[mfa_user]
aws_access_key_id = ABCD$$$$$$$$
aws_secret_access_key = knklvdf093487jps/df\$$$$$$$$$$$$$$$$$$$$$$
Enter fullscreen mode Exit fullscreen mode

2. Lets create role profile

To create a role profile add admin_role profile section in ~/.aws/config.

[profile admin_role]
role_arn = arn:aws:iam::<account_number>:role/admin_mfa
source_profile = mfa_user
mfa_serial = arn:aws:iam::<account_number>:mfa/mfa  
Enter fullscreen mode Exit fullscreen mode

You can get role_arn from terraform output. Get MFA Serial from AWS Console.

3. Now you can use aws cli with admin_role profile

aws s3 ls --profile admin_role
Enter fullscreen mode Exit fullscreen mode

terraform

If you enable MFA, configuring terraform gets a bit hacky. You can use following script to automate this process.

#!/usr/bin/env bash

echo "totp is $1"

ROLE_ARN="arn:aws:iam::<account_number>:role/admin_role"
MFA_ARN="arn:aws:iam::<account_number>:mfa/mfa"

aws sts assume-role \
    --role-arn $ROLE_ARN \
    --role-session-name session-one \
    --serial-number $MFA_ARN \
    --token-code $1 > /tmp/sts.json

aws configure set aws_access_key_id $(cat /tmp/sts.json | jq -r '.Credentials.AccessKeyId') --profile terraform
aws configure set aws_secret_access_key $(cat /tmp/sts.json | jq -r '.Credentials.SecretAccessKey') --profile terraform
aws configure set aws_session_token $(cat /tmp/sts.json | jq -r '.Credentials.SessionToken') --profile terraform
aws configure set region "ap-southeast-1" --profile terraform

rm /tmp/sts.json
Enter fullscreen mode Exit fullscreen mode

you can use this script with ./auth.sh <6 Digit MFA Code>. This will configure aws profile named terraform. You can configure terraform aws provider with with this profile.

provider "aws" {
  profile = "terraform"
}
Enter fullscreen mode Exit fullscreen mode

AWS Console

Use Switch role button to switch to admin role after signing in to AWS Console.

Image description

Top comments (0)