Table of Contents

, , , ,

AWS CLI with 2FA

If 2FA is enabled on your AWS account, in order to use aws cli command from terminal you need to get the fresh credentials. First get the arn:

aws iam list-mfa-devices --user-name meandmyself

Then get the creds:

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

The arn-of-the-mfa-device is from the first command and code-from-token is just the 6-digit code from your 2FA app on your phone or somewhere.

Then copy paste all of the fields in ~/.aws/credentials file.

Example:

antisa@antisa-XPS-13-9310:~$ aws iam list-mfa-devices
{
    "MFADevices": [
        {
            "UserName": "ante",
            "SerialNumber": "arn:aws:iam::xxxxxxxxxxxx:mfa/meandmyself",
            "EnableDate": "2024-05-09T11:50:38+00:00"
        }
    ]
}

antisa@antisa-XPS-13-9310:~$ aws sts get-session-token --serial-number arn:aws:iam::xxxxxxxxxx:mfa/meandmyself --token-code 123456
{
    "Credentials": {
        "AccessKeyId": "ASxxxxxxxxxxxx",
        "SecretAccessKey": "wBxxxxxxxxxxxxxxxxxxxxxxxx",
        "SessionToken": "IQoJb3xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
        "Expiration": "2024-10-16T23:56:17+00:00"
    }
}

The format in ~/.aws/credentials should be like:

[myprofile]
aws_access_key_id = xxxxxxxxxxxxxxxxxxx
aws_secret_access_key = xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
aws_session_token = IQoxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

Tested on

See also

References