How to use the AWS CLI with MFA required

How to use the AWS CLI with MFA required

A very short post only containing the juicy parts, let's get into it.👀


I recently had to interact with an AWS account that requires MFA for all users. This is okay in the console since it simply tells you that it needs the MFA code. The CLI is different however, because it only outputs a generic AccessDenied error. If MFA is required on the account for all interaction (via SCPs for example), this is how you can still use the CLI with MFA credentials.


You have to request a seperate access & secret key and a session token from AWS via the CLI. You have to execute the following command with a pair of access keys that have access to that account normally. This can be executed without any MFA restrictions (it would be pretty funny to require MFA to ask for MFA credentials haha).

aws sts get-session-token \
--serial-number arn:aws:iam::{AWS::AccountId}:mfa/{User} \
--profile user@yourAccount \
--token-code mfa-code-from-device

Let's break that down:

  • aws sts get-session-token is self-explanatory. This is the command to request the pair of access keys and a session token with MFA "embedded".
  • --serial-number arn:aws:iam::{AWS::AccountId}:mfa/{User} refers to the ARN of the MFA device in your user account. You can find this in the IAM console under your user. Make sure to replace {AWS::AccountId} with your actual account ID, eg. 4567325783.
  • --profile user@yourAccount refers to your local setup. I don't have a default CLI profile and I force myself to use the profile flag for every command. You might not have this, just make sure you are executing this command with a pair of access keys that belong to the AWS account you want to have MFA credentials for.
  • --token-code mfa-code-from-device is the MFA code from your device. Replace the mfa-code-from-device with the current code (eg. 452455).


This will output an Access Key, a Secret Key and a Session Token. You have to save all these into a profile in your ~/.aws/credentials file. You can name this profile anything, I tend to name it mfa.

aws_access_key_id = example
aws_secret_access_key = example
aws_session_token = example


You can use this profile just like every other, with the --profile mfa flag. Note that these credentials are only live for 12 hours from creation, so you'll likely have to do this every day. I haven't found a better soluion as of yet, but if you do have something then please let me know😈

Photo by chris panas on Unsplash