How to Set Up and Use MFA with AWS CLI for Secure API Access

Your AWS CLI commands won’t run until you prove you are you. That’s the point of Multi-Factor Authentication, and in AWS CLI, it’s both strict and simple if you set it up right. Miss a step, and every API call fails. Get it right, and you keep attackers out without slowing yourself down.

What is AWS CLI MFA
AWS CLI Multi-Factor Authentication (MFA) requires an extra verification step before you run commands. This step ensures that even if your AWS access keys are exposed, no one can use them without a one-time code from your MFA device. It works with both virtual and hardware MFA devices linked to your AWS IAM user.

How AWS CLI MFA Works
When you have MFA enforced at the AWS account or IAM policy level, API calls need temporary security credentials. These credentials come from the sts get-session-token command, which takes your MFA device serial number and your current token code. After you get the session token, you use it for all CLI calls until it expires.

Step-by-Step AWS CLI MFA Setup

  1. Open the AWS Management Console and attach an MFA device to your IAM user. Use the Security Credentials tab.
  2. On your machine, check your AWS CLI is updated to the latest version.
  3. Find your MFA device serial:
aws iam list-mfa-devices --user-name YourUserName
  1. Generate a session token:
aws sts get-session-token \
 --serial-number arn:aws:iam::123456789012:mfa/YourUserName \
 --token-code 123456
  1. Export the credentials to your shell:
export AWS_ACCESS_KEY_ID=TempAccessKey
export AWS_SECRET_ACCESS_KEY=TempSecretKey
export AWS_SESSION_TOKEN=TempSessionToken
  1. Run your normal CLI commands with these temporary credentials until they expire.

Tips for AWS CLI MFA Efficiency

  • Automate the get-session-token process with a shell script.
  • Store temporary credentials in a dedicated AWS CLI profile to avoid overwriting long-term credentials.
  • Reduce MFA friction by pairing it with short, reusable scripts or credential managers.

Security Benefits
AWS CLI MFA protects your infrastructure against stolen keys. Even if an attacker has your access key and secret key, they can’t call the AWS API without the MFA code. This aligns with best security practices and most compliance frameworks.

Example of an MFA-Aware CLI Workflow

  1. Run MFA session script.
  2. Switch profile to mfa profile using:
aws s3 ls --profile mfa
  1. Repeat until token expiration, then re-run the MFA step.

You can have AWS CLI MFA running in minutes and see exactly how it fits your workflow with zero risk. Build, secure, and test API calls faster — start live now with hoop.dev.