Sobes.tech
Junior — Middle

How can you set up two-factor authentication for AWS commands via CLI?

sobes.tech AI

Answer from AI

To set up two-factor authentication (MFA) when working with AWS CLI, follow these steps:

  1. Configure MFA device in AWS IAM — in the AWS console, under IAM, add an MFA device (for example, a virtual application like Google Authenticator) to your account or user.

  2. Obtain temporary session tokens with MFA — AWS CLI does not support MFA directly in a regular call, so you need to use the command aws sts get-session-token specifying the MFA device's serial number and the current code:

aws sts get-session-token --serial-number arn:aws:iam::123456789012:mfa/your-user --token-code 123456
  1. Use the obtained temporary credentials — the command will return temporary access keys (AccessKeyId, SecretAccessKey, SessionToken), which should be used for subsequent AWS CLI calls.

  2. Configure AWS CLI profile with temporary keys — you can save them in a separate profile or export them as environment variables:

export AWS_ACCESS_KEY_ID=...
export AWS_SECRET_ACCESS_KEY=...
export AWS_SESSION_TOKEN=...

Thus, each time you work with AWS CLI with MFA, you need to obtain temporary tokens via sts get-session-token, using the code from the MFA device.

Automation script example:

MFA_SERIAL=arn:aws:iam::123456789012:mfa/your-user
TOKEN_CODE=$(read -p "Enter MFA code: " code && echo $code)

CREDS=$(aws sts get-session-token --serial-number $MFA_SERIAL --token-code $TOKEN_CODE --output json)

export AWS_ACCESS_KEY_ID=$(echo $CREDS | jq -r '.Credentials.AccessKeyId')
export AWS_SECRET_ACCESS_KEY=$(echo $CREDS | jq -r '.Credentials.SecretAccessKey')
export AWS_SESSION_TOKEN=$(echo $CREDS | jq -r '.Credentials.SessionToken')

This will ensure two-factor authentication when working with AWS CLI.