
Use this bash script to automatically identify and deactivate IAM access keys that haven't been used in 6 months or have never been used. This improves security posture by reducing the attack surface from stale credentials.
Introduction
Managing access keys for IAM users in AWS is a critical task to ensure the security and compliance of your cloud infrastructure. Access keys provide programmatic access to AWS services and resources, and it's essential to regularly review and deactivate unused or unnecessary keys. However, manually performing this task can be time-consuming and error-prone, especially in large-scale environments. In this post, we will explore how to automate access key management using a bash script and the AWS CLI. We'll look at a practical example that checks the last usage date of access keys for IAM users and deactivates keys that have not been used for 6 months or have never been used.
Welcome to this step-by-step guide on 'IAM Key Spring Cleaning'. By automating access key management with this script, you can enhance your security posture, reduce manual effort, and ensure that access keys are regularly reviewed and deactivated when necessary.
Deactivating access keys can break applications that depend on them. Before running this script in production, identify all applications using access keys and coordinate key rotation with application owners.
Use This
- AWS CloudShell
- Bash Script
Do This
- Open CloudShell
- Create bash file: touch deactivateIAMkeys.sh
- Create contents of bash file: vi deactivateIAMkeys.sh
- Type in code below
- Save the file
- Change the file to an executable file: chmod +x deactivateIAMkeys.sh
- Run the script: ./deactivateIAMkeys.sh
Start by running the script in report-only mode (comment out the update-access-key line) to generate a list of keys that would be deactivated. Share this report with stakeholders before actually deactivating keys.
Write This
The script structure is straightforward: a nested loop using the AWS CLI.
- Compute a six-months-ago timestamp once at the start with
date -d "6 months ago" +%s. - Outer loop:
aws iam list-usersto get every IAM user. - Inner loop: for each user,
aws iam list-access-keysto get their key IDs. - For each key, call
aws iam get-access-key-last-usedand parseAccessKeyLastUsed.LastUsedDatewithjq. - If the LastUsedDate is
null, the key has never been used: deactivate it viaaws iam update-access-key --status Inactive. - Otherwise convert the date to a Unix timestamp and compare against the six-months-ago cutoff. If older, deactivate.
A core CLI shape worth remembering:
aws iam update-access-key --user-name $user --access-key-id $key --status Inactive
Gotcha: date -d is GNU date. On macOS you'd need date -v-6m +%s. Also: run in report-only mode first. Comment out the update-access-key call and just echo what would happen. Share the report with stakeholders so you don't break a forgotten production app at 2 AM.
This script requires jq to be installed for JSON parsing. CloudShell has jq pre-installed. Modify the "6 months ago" value to match your organization's key rotation policy.
What The Heck Does This Code Do
- Get today's date and set up/calculate a variable for a date 6 months ago
- Find all the users in IAM
- Check to see if the user has any access keys
- Get the last date the user used the access key
- If the user never used the access key, deactivate the key
- If the user hasn't used the access key in the last 6 months, deactivate the key
Troubleshooting
Common Issues and Solutions
Application Stops Working After Key Deactivation
- Problem: An application fails after its access key was deactivated
- Solution: Reactivate the key immediately with: aws iam update-access-key --user-name USER --access-key-id KEY --status Active. Then work with the application owner to rotate to a new key.
jq Command Not Found
- Problem: Script fails with jq not found error
- Solution: Install jq using your package manager (apt-get install jq, yum install jq). In CloudShell, jq is pre-installed.
Date Command Syntax Error
- Problem: Date calculation fails on macOS
- Solution: macOS uses BSD date, not GNU date. Use: six_months_ago=$(date -v-6m +%s) instead of date -d.
Permission Denied on IAM Operations
- Problem: Access denied when listing users or updating keys
- Solution: Ensure your IAM user/role has iam:ListUsers, iam:ListAccessKeys, iam:GetAccessKeyLastUsed, and iam:UpdateAccessKey permissions.
Script Takes Too Long
- Problem: Script runs for hours in accounts with many users
- Solution: Run the script in batches by modifying the user query to limit results, or parallelize the key checks using GNU parallel.
Till Next Time
Automating access key management in AWS IAM with bash scripting offers numerous benefits in terms of security, efficiency, and compliance. In this post, we explored a practical example of a bash script that utilizes the AWS CLI to check the last usage date of access keys for IAM users and deactivate keys that have not been used for 6 months or have never been used.
By implementing this script, you can streamline the process of access key management, ensuring that inactive or unnecessary keys are promptly deactivated. This helps mitigate the risk of unauthorized access and strengthens the overall security posture of your AWS environment.
Moreover, the script serves as a foundation for customization and extension. You can tailor it to suit your specific requirements, such as sending notifications or integrating it with other processes in your infrastructure.
As your AWS environment evolves, it is key to stay proactive in managing access keys and maintaining a strong security stance. Automating access key management with the power of bash scripting and the AWS CLI enables you to efficiently handle this critical aspect of IAM, allowing you to focus on other essential tasks and ensuring the ongoing integrity and security of your AWS resources.
In the dynamic and often complex world of cloud computing, it's the small things that can make a big difference. And remember, consistent cloud cleanliness is next to digital godliness. So, keep your digital broom at the ready, sweep away unnecessary objects, and keep your cloud environment running at its peak potential. Until next time, happy 'Spring Cleaning'!
Want Help With This?
If you're working on something similar and want a second set of eyes, or you'd like to talk through how this applies to your environment, reach out via the contact form. Happy to help.