User Tools

Site Tools


wiki:aws_cli_2fa

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

  • aws-cli/2.12.5 Python/3.11.4 Linux/6.8.0-45-generic exe/x86_64.ubuntu.22 prompt/off

See also

References

wiki/aws_cli_2fa.txt · Last modified: 2024/10/16 14:18 by antisa

Except where otherwise noted, content on this wiki is licensed under the following license: CC0 1.0 Universal
CC0 1.0 Universal Donate Powered by PHP Valid HTML5 Valid CSS Driven by DokuWiki