Skip to main content
Skip table of contents

Set up AWS Command Line Interface (AWS CLI) to use Multi-factor Authentication (MFA)

This document outlines how to configure the AWS CLI to work with MFA. If you encounter “Unauthorized” errors while attempting to use the AWS CLI, this may help.

Note: Make sure you have already set up your AWS account using these instructions.

The examples below were performed on Ubuntu using jq and may need to be adjusted for other operating systems or environments.

How to set up AWS CLI to use MFA

Get the ARN of your MFA device used with your AWS account

BASH
MFA_ARN=$(aws iam list-mfa-devices --query 'MFADevices[].SerialNumber' --output=text)

Make sure you have your MFA open to get the appropriate token

Note: The default token life is 12 hours. See note at the bottom of this page for Token Expiration Duration parameters.

BASH
aws sts get-session-token --serial-number "$MFA_ARN" --token-code <token_from_mfa> > ~/.aws/session_token.json

Set up environment secret variables for AWS CLI

BASH
jq -r '.Credentials | "AWS_ACCESS_KEY_ID='\''" + .AccessKeyId + "'\''", "AWS_SECRET_ACCESS_KEY='\''" + .SecretAccessKey + "'\''", "AWS_SESSION_TOKEN='\''" + .SessionToken + "'\''"' ~/.aws/session_token.json

This will produce output similar to this:

CODE
AWS_ACCESS_KEY_ID='<20 character long ID'
AWS_SECRET_ACCESS_KEY='<40 character long key>'
AWS_SESSION_TOKEN='<276 character long token>'

Use awk to export the variables in one line, wrapped up in an eval

BASH
eval "$(jq -r '.Credentials | "AWS_ACCESS_KEY_ID='\''" + .AccessKeyId + "'\''", "AWS_SECRET_ACCESS_KEY='\''" + .SecretAccessKey + "'\''", "AWS_SESSION_TOKEN='\''" + .SessionToken + "'\''"' ~/.aws/session_token.json | awk -v ORS=" " 'BEGIN{print "export"} {print}')"

Verify that you can perform AWS CLI commands

CODE
aws ec2 describe-instances --region us-gov-west-1

Token Expiration Duration: You can specify an expiration duration (in seconds) using the --duration-seconds option in the sts get-session-token command, where the value can range from 900 seconds (15 minutes) to 129600 seconds (36 hours). If you are using root user credentials, then the range is from 900 seconds (15 minutes) to 3600 seconds (1 hour).


JavaScript errors detected

Please note, these errors can depend on your browser setup.

If this problem persists, please contact our support.