Script: Get Temporary AWS Credentials at the Command Line with MFA

set-sts-creds.sh

Introduction

So you have followed best practices for AWS, you have implemented multiple factor authentication for your account and you have separated different environments into separate accounts under a master organization. But now you are facing a problem, you need to use a tool such as Terraform that does not understand how to handle MFA and you are unable to assume the proper role because of that. This script takes care of that issue. This script is very simple, it uses your existing AWS CLI credentials file, gets your MFA token, and sets temporary credentials in the proper environment variables so that Terraform and other tools can access them.

Prerequisites

This script requires a BASH environment, the AWS command line tools, and JQ to be installed in order to function properly.

The script

Here is the script in its entirety. Full script can be found at GitHub link found later in the article

Breaking it Down

Section 1: Starting Simple

Full script can be found at GitHub link found later in the article In this section we are doing two basic things. The first is the typical bash shebang line.

Next, we unset the appropriate AWS environment variables. If we don't do this, the script will fail if these have already been set.

Section 2: Get MFA

Full script can be found at GitHub link found later in the article Here you will need the arn of your MFA device. This can be found on your security credentials page in IAM. We set that to a variable and then we prompt the user to provide the MFA code that is currently displayed on the device.

Section 3: Making the Request

Full script can be found at GitHub link found later in the article In this section we are making a request to the STS service and storing the result in a variable.

Section 4: Parsing the Response

Full script can be found at GitHub link found later in the article Now, we are using JQ to get parse the response and get the individual pieces of the credentials and store them in separate variables.

Section 5: Display the Response

Full script can be found at GitHub link found later in the article This part of the script is quite optional, but I like to display the parsed credentials to the user so that they can confirm that things worked properly.

Section 6: Clean-up the Environment

Full script can be found at GitHub link found later in the article Lastly, we strip the quotes from the values and store them in the appropriate AWS environment variables. The piped sed is the fastest and easiest way to get clean values.

Bring it all together

The final piece of this particular puzzle is that you cannot just run it. It won't set the environment variables in the way that you would expect, so you need to source it. I setup an alias in my profile like this: alias set-aws-creds = "source ~/scripts/set-aws-creds.sh"

You can find the full code for this script in my GitHub scripts repository