Accessing AWS with MFA via CLI

Swateek Jena
Noob Techie
Published in
2 min readNov 15, 2022

If your AWS account is MFA enabled, you cannot use your credentials to directly access any AWS resources. You’ll need a session token in that case.

Pre-Requisites

  • if you are to use via CLI, you need to have aws-cli installed.
  • if you want to have boto3, use pip to install the same
  • The MFA ARN — can be found under the “Security Credentials” option from the drop-down on the right top of the AWS Console page.
ARN for MFA device

Accessing via CLI

Replace the AWS_MFA_CONFIG with the ARN of the MFA device you got from the console above.

Save the below snippet in a shell script named, fetch_mfa.sh

Give execute permission to the script using the chmod command

AWS_SRC_PROFILE=default
AWS_DEST_PROFILE=mfa
AWS_MFA_CONFIG=<MFA>
AWS_MFA_TOKEN=$1

aws --profile ${AWS_SRC_PROFILE} sts get-session-token --duration 129600 --serial-number ${AWS_MFA_CONFIG} --token-code ${AWS_MFA_TOKEN} | jq -r '@sh "export TMP_AWS_ACCESS_KEY_ID=\(.Credentials.AccessKeyId)\nexport TMP_AWS_ACCESS_KEY_SECRET=\(.Credentials.SecretAccessKey)\nexport TMP_AWS_SESSION_TOKEN=\(.Credentials.SessionToken)"' > .aws_mfa.creds

source .aws_mfa.creds
aws configure set aws_access_key_id ${TMP_AWS_ACCESS_KEY_ID} --profile mfa
aws configure set aws_secret_access_key ${TMP_AWS_ACCESS_KEY_SECRET} --profile mfa
aws configure set aws_session_token ${TMP_AWS_SESSION_TOKEN} --profile mfa

rm -rf .aws_mfa.creds
aws s3 ls --profile mfa

How to run the script?


./fetch_mfa.sh <token-from-device>

Accessing via boto3

Save the following snippet in a file name, mfa.py

#!./venv/bin/python

import boto3, pprint

pp = pprint.PrettyPrinter(indent=2)
boto3.setup_default_session(
profile_name="default"
) # this is optional if profile is "default"
client = boto3.client("sts")

mfa_serial_number = "<enter MFA ARN>"
mfa_totp = "<enter MFA TOTP from device>"

response = client.get_session_token(SerialNumber=mfa_serial_number, TokenCode=mfa_totp)
pp.pprint(response)

--

--