Sometimes you may need to connect to AWS environments with MFA enforced using AWS CLI. If you don´t authenticate with MFA, you got high probabilities to obtain a denied access.
With this process, you will be able to authenticate with MFA over CLI.
1-Connect to AWS CLI.
>$ aws configure
>AWS Access Key ID: Your access key
>AWS Secret Access Key: Your secret access key
>Default Region Name: select one
>Default Output Format: JSON (this is very important, if you use “text” the data may not be easily legible)
2-Create a Session
$ aws sts get-session-token –serial-number arn-of-the-mfa-device –token-code code-from-token
arn-of-the-mfa-device: You can find it in the “My Security Credentials” Section of your AWS console
And once in, scroll down to “Assigned MFA Device”. You will find your MFA Serial.
Get a code from your authenticator and replace with it code-from-token.
You will obtain an output like this
“Credentials”: {
“AccessKeyId”: “ASMRSPBWPXZ36YIOXP”,
“SecretAccessKey”: “zzcIUMnGTB8jdXvSwUvQDV4EFdkuag/xdPEjC/”,
“SessionToken”: “FQoGZXIvYXdzEFYaDGelNXKWLJk0XpMppSKwAcP8UQcfzQBOFKsq0G9W810djGYQ95qoBft3htVHM0jI7Df4aDgXI/OKHYUTLKGKG9pGeNYxg7w8977H9SUBmMxCBy37Jfm8oVeWpLZIj76RP7PzaFJum5vFYHfX3zzzGS5KWUOQCqcn5147C7RkT72fHeex2tHDKQLG72ayjfZpfskCV99DglkkyTz8Mi+8Q0gcociD5s+KJyTsOQF”,
“Expiration”: “2019-03-16T08:22:52Z”}
Now, set the console with the data you obtained
>set AWS_ACCESS_KEY_ID=<Access-Key-as-in-Previous-Output>
> set AWS_SECRET_ACCESS_KEY=<Secret-Access-Key-as-in-Previous-Output>
> set AWS_SESSION_TOKEN=<Session-Token-as-in-Previous-Output>
After that, you will be able to execute commands on AWS CLI with access granted.
This session will typically expire after 12 hours. Anyway, a good idea it´s remove the parameters once finished.
> unset AWS_ACCESS_KEY_ID
> unset AWS_SECRET_ACCESS_KEY
> unset AWS_SESSION_TOKEN