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.
This script requires a BASH environment, the AWS command line tools, and JQ to be installed in order to function properly.
Here is the script in its entirety.
Breaking it Down
Section 1: Starting Simple
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
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
In this section we are making a request to the STS service and storing the result in a variable.
Section 4: Parsing the Response
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
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
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