How to use MFA with AWS CLI

In this article, we will dive in and see how to login using MFA with AWS CLI.

Prerequisites

  • AWS CLI is set up
  • IAM user is already configured using “aws configure” command
  • MFA is enabled for this IAM user

GetSessionToken API

The API we will use for using MFA with AWS CLI is GetSessionToken from AWS STS service. GetSessionToken API will accept the code from MFA device and return temporary credentials that could be used to make API calls that require MFA authentication. These temporary credentials returned by the GetSessionToken API, will have the same permissions as the IAM user.

The GetSessionToken API itself will be made using long term AWS security credentials; in the case of CLI, using the Access Key ID and Secret Access Key of the IAM user.

Steps

Execute the below command by providing the ARN of the MFA device configured for the IAM user and the token code from the MFA device.

aws sts get-session-token --serial-number mfa-device-arn --token-code mfa-token-code

The above command would return the temporary security credentials as below

{
    "Credentials": {
        "AccessKeyId": "ASIASALD7UD2WRA6TMLI",
        "SecretAccessKey": "n1UEgvlj2dVbcbYvBctAjEX1dW",
        "SessionToken": "IQoJb3JpZ2luX2VjEKX//////////wE..",
        "Expiration": "2022-12-04T00:37:05+00:00"
    }
}

We can use these temporary security credentials by either setting them in the environment variables or by creating a new profile and setting the credentials in the .aws/credentials file.

Setting using environment variables

Windows

set AWS_ACCESS_KEY_ID=ASIASALD7UD2WRA6TMLI
set AWS_SECRET_ACCESS_KEY=n1UEgvlj2dVbcbYvBctAjEX1dW
set AWS_SESSION_TOKEN=IQoJb3JpZ2luX2VjEKX//////////wE..

Mac

export AWS_ACCESS_KEY_ID=ASIASALD7UD2WRA6TMLI
export AWS_SECRET_ACCESS_KEY=n1UEgvlj2dVbcbYvBctAjEX1dW
export AWS_SESSION_TOKEN=IQoJb3JpZ2luX2VjEKX///////wE..

Once these temporary security credentials are set using the environment variables, you can invoke API calls normally through CLI and it would use these temporary credentials.

Setting using profiles in the .aws/credentials file

Open up the .aws/credentials file and edit the file as below to create a new profile and set the temporary credentials received from GetSessionToken API.

[mfa]
aws_access_key_id=ASIASALD7UD2WRA6TMLI
aws_secret_access_key=n1UEgvlj2dVbcbYvBctAjEX1dW
aws_session_token=IQoJb3JpZ2luX2VjEKX//////////wE..

Once the profile is created and the credentials set, make sure to use the profile while making API calls in the AWS CLI.

aws s3 ls --profile mfa

That’s it for using MFA with CLI. Thanks for reading!

References and further reading

1 thought on “How to use MFA with AWS CLI”

Leave a Comment

Your email address will not be published. Required fields are marked *