May 18, 2018

Using AWS CLI tools with MFA enabled on your account

Say your all-powerful AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY have lost their AWS CLI powers because your Amazon Web Services account is now secured with multi-factor authentication. How are you going to automate wicked cool tasks restoring DynamoDB tables or creating Snowball export jobs that your application’s service accounts aren’t authorized to do?

Security Token Service (sts) to the rescue!

There’s a set of commands under the sts namespace in the AWS CLI tools which will help you out.

What is STS?

The AWS Security Token Service (STS) is a web service that enables you to request temporary, limited-privilege credentials for AWS Identity and Access Management (IAM) users or for users that you authenticate (federated users).

You are going to use AWS STS via the AWS CLI to generate new AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY that is MFA approved so you can get back to stopping matchmaking tickets in Game Lift whenever you feel like it.

The commands

First up, some environment assumptions:

Grab your MFA device, and get a code ready to put in the --token-code parameter.

$ aws sts get-session-token --serial-number arn:aws:iam::479113801439:mfa/my.name --token-code 111111

Your new temporary credentials

Run the command and you should see output like this (my profile defaults to JSON output):

{
  "Credentials": {
    "AccessKeyId": "<temporary secret stuff>",
    "SecretAccessKey": "<temporary secret stuff>",
    "SessionToken": "<temporary secret stuff>",
    "Expiration": "<temporary secret stuff>"
  }
}

This is a new set of temporary credentials that have authenticated wih MFA. Once again, you have the power!

Using the new credentials

Put the first 3 properties in your ~/.aws/credentials file under a new profile (I chose mfa, but it can’t be anything):

[default]
aws_access_key_id=<secret stuff>
aws_secret_access_key=<secret stuff>

[mfa]
aws_access_key_id=<temporary secret stuff>
aws_secret_access_key=<temporary secret stuff>
aws_session_token=<temporary secret stuff>

You might also need to add the new profile to ~/.aws/config depending on which AWS services you are running.

Now try running a command that failed because of MFA with your new mfa profile

aws dynamodb list-tables --profile mfa

The new MFA-authorized credentials will be submitted to AWS with your request, and your command will work.