Learn how to Automate AWS IAM Key Rotation
Introduction
We all know how difficult is to manage and rotate AWS IAM keys, there are a lot of tools out there that can help you manage your keys easly but in this blog post I will tell you about the process and introduce you a new tool for key rotation.
Let's first touch base...
What is IAM
AWS Identity and Access Management (IAM) is a web service that helps you securely control access to AWS resources. You use IAM to control who is authenticated (signed in) and authorized (has permissions) to use resources.
Key rotation
Changing access keys (which consist of an access key ID and a secret access key) on a regular schedule is a well-known security best practice because it shortens the period an access key is active and therefore reduces the business impact if they are compromised.(reference)
To manually rotate keys AWS has documented steps needed to follow but this is a bit pain...
To rotate access keys, you should follow these steps:
Create a second access key in addition to the one in use.
Update all your applications to use the new access key and validate that the applications are working.
Change the state of the previous access key to inactive.
Validate that your applications are still working as expected.
Delete the inactive access key.
To get rid of all of this pain let me introduce you to the aws-iam-key-rotation
tool that will help rotation your keys automagically
Let's dig a bit deeper...
How does it work?
This script uses AWS CLI to rotate keys, in order to work you should add aws profile name and IAM user as parameter.
Prerequisites
- awscli (docs.aws.amazon.com/cli/latest/userguide/cl..)
- jq (sudo apt-get install -y jq or brew install jq)
Usage:
./aws-iam-key-rotation.sh aws-cli-profile iam-user-name
There are two cases covered by script
- If user has only one key configured
- If user has two keys configured
Screenshots:
If user has only 1 key configured
It will create new key - check if key works properly, set it up on existing aws cli profile and delete the old one.
If user has 2 keys configured
It will deactivate and delete the oldest key.
Automating the process
In this example I will be using crontab to schedule script to run every day at 00:00
- First run
crontab -e
- At the beginning of the crontab file add this line
SHELL=/bin/bash
0 0 * * * /path/to/script/aws-iam-key-rotation.sh <aws-cli-profile> <iam-user-name>
(if you want to see the logs of each triggered job you can add this>> /path/to/log/file
at the end of command) E.g0 0 * * * /path/to/script/aws-iam-key-rotation.sh <aws-cli-profile> <iam-user-name> >> /path/to/log/file
- Save it and wait for magic to happen :)
Hope you enjoyed reading this blog post :)
Thank you !