Introduction
Access to some AWS resources require an AWS Security Token Service session where an MFA key has been used to generate temporary security credentials for an IAM User. This page provides details on how to use MFA and STS together on the command line with AWS CLI (v1).
Prerequisites
- Identity the IAM user that you will be using with STS.
- This IAM user must have access keys. Here's how to create and manage access keys for your IAM user: https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_access-keys.html
- This IAM user must have an MFA device set. Here's how to manage MFA for your IAM user: https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_mfa_enable.html
- Ensure that the AWS CLI is configured to use your IAM user access keys. Here's how: https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-configure.html#cli-quick-configuration
Generating Temporary Security Credentials
Example CLI
# Confirm that IAM user credentials are working $ aws sts get-caller-identity { "UserId": "AIDAXXXXXXXXXXXXXXXXX", "Account": "123456789012", "Arn": "arn:aws:iam::123456789012:user/pea1" } # Generate temporary credentials. The code from the MFA is "987654" at the time the command is executed $ aws sts get-session-token --serial-number arn:aws:iam::123456789012:mfa/pea1 --token-code 987654 { "Credentials": { "AccessKeyId": "ASIAYYYYYYYYYYYYYYYY", "SecretAccessKey": "ABC****************************************", "SessionToken": "DEF********************************************************************************", "Expiration": "2020-06-13T01:29:49Z" } } # Setup environment to use the new temporary credentials $ export AWS_ACCESS_KEY_ID=ASIAYYYYYYYYYYYYYYYY $ export AWS_SECRET_ACCESS_KEY=ABC**************************************** $ export AWS_SESSION_TOKEN=DEF******************************************************************************** # Unfortunately, you cannot tell that the new session is temporary or that MFA was involved. $ aws sts get-caller-identity { "UserId": "AIDAXXXXXXXXXXXXXXXXX", "Account": "123456789012", "Arn": "arn:aws:iam::123456789012:user/pea1" } $
See also https://aws.amazon.com/premiumsupport/knowledge-center/authenticate-mfa-cli/