Use AWS CLI With MFA
When you have MFA enabled in your AWS account, certain commands may not work with a simple access key and secret key. You need to get a session token and use that instead. Here are the steps to get a session token.
- Make sure you AWS CLI installed and configured with your access key and secret key. Following steps assume that these credentials are set as the default profile; if not, then add
--profile profile-name
at the end of each command. - Find out the ARN of you MFA device.
aws iam list-mfa-devices
- Get code from your MFA device.
- Get a session token.This will return an output like this:
aws sts get-session-token --serial-number arn-of-the-mfa-device --token-code code-from-mfa-device
{ "Credentials": { "SecretAccessKey": "secret-access-key", "SessionToken": "temporary-session-token", "Expiration": "expiration-date-time", "AccessKeyId": "access-key-id" } }
- Add these credentials to your AWS CLI configuration. Change
--profile mfa
to whatever profile name you want to use.aws configure set aws_access_key_id access-key-id --profile mfa aws configure set aws_secret_access_key secret-access-key --profile mfa aws configure set aws_session_token temporary-session-token --profile mfa
- You can now use the
mfa
profile to run commands that require MFA.aws s3 ls --profile mfa