It’s a good practice to rotate your AWS CLI keys periodically. Recently I wrote a key rotation shell script to match a company policy where an IAM user is allowed to have the maximum of two concurrent keys. If both “slots” are taken when the script is triggered, it looks at the creation dates/times of the keys, which key is currently active (or if both are), and which one is currently configured in the users’s `~/.aws/config` file (and hence is being used for the rotation operation), and then allows the user to delete the key that is either older, or not currently in use, thus making space for a new key.
Once the new key is generated, the script activates the key, tests that it works, and then removes the key that the new key replaces.
The script was created and tested for use on macOS, but it will likely work on Linux as well (I will soon test it on Linux and make any portability changes if needed).
You can find aws-iam-rotatekeys.sh script on GitHub.
Update 28 October 2017: An improved version of the script has been published.
See the details here!
6 thoughts on “A Convenient AWS CLI Key Rotation Script for IAM Users”
Ville – did you try this on Linux? If so, do you have a URL to the updated script?
Hi Doug – I haven’t tried it on Linux yet. I see if I’d have time to take a look at it this week.
The new version is now available! See the details here!
How i can rotate IAM keys for all the IAM users every 3 months and then send out to the users.
Can you please advise me on this?
This script is meant for rotating just the user’s own keys (i.e. those that are located in `~/.aws/credentials`). However, it is possible to rotate other IAM users’ access keys as well. See this link for additional information. AWS does not provide a mechanism for distributing the keys to the users, so you would have to set something secure up for that. Depending on the number of the users, you might use keybase.io to transit the new keys to them manually but securely (if there are few users), or perhaps have a S3 bucket where new IAM users are automatically assigned a folder (perhaps by the same name as their IAM username) that only they have access to. The new keys would be deposited there… however, if you deactivate or delete their previous keys upon rotation, they obviously would no longer have access to the bucket containing their folder, so you’ll have to consider what would work best in your use case.
I would also recommend enforcing 2-factor authentication, including in CLI (with a session token that would have maybe 6-12 hour lifetime). See the article “Easy MFA and Profile Switching in AWS CLI” for more details about that.
While the script works great, I found that if I have multiple AccessKey IDs, it deletes both of them, instead of the one I selected. And then creates a fresh AccessKey ID.
This can cause problem if I use 2 different AccessKey ID for 2 different applications, it will delete both instead of the intended one. Is this an intended behaviour?