100 Days of AWS — Day 25- Rotating IAM Keys on a regular basis using Boto3
To view the complete course, please enroll it using the below link(it’s free)
https://www.101daysofdevops.com/courses/100-days-of-aws/
Welcome to Day 25 of 100 Days of AWS. The topic for today is Rotating IAM Keys on a regular basis using Boto3
This is another common use case we use to encounter as a part of daily DevOps job where we need to rotate the IAM key as per company policy(for e.g., every 30 or 60 days). One of the primary reasons to rotate these keys is to follow the best security practice and reduce the blast radius if these keys got compromised.
To write this code, we need to follow the series of steps
Step1: Importing the standard library boto3 and datetime module.
import boto3
from datetime import datetime, timezone
Step2: Create the IAM client
client = boto3.client("iam")
Step3: Next step is to use a paginator. This step is only required if you have more than 100 IAM users in your account. As the default page size for IAM is only 100.
paginator = client.get_paginator('list_users')
Step4: We need to capture the current date and for this demo, set the maximum key age as 5 days.
current_date=datetime.now(timezone.utc)
max_key_age=5
Step5: As the next step, we need to get the list of all the users.
for response in paginator.paginate():
for user in response['Users']:
username = user['UserName']
Step6: Using list_access_keys and passing the username, we will get some metadata like access key id and key creation date.
accesskey_id = accesskey['AccessKeyId']
key_creation_date = accesskey['CreateDate']
Step7: In the next step, we will determine the current date vs. when the key is created. If this diff is greater than max_key_age, then deactivate the key for the user.
age = (current_date - key_creation_date).days if age > max_key_age:
Step8: To deactivate the key for the user, we need to use the update_access_key() method and pass arguments like username, access key id, and set Status=Inactive.
print("Deactivating Key for the following users: " + username)
client.update_access_key(UserName=username, AccessKeyId=accesskey_id, Status='Inactive')
NOTE: Before deactivating the key for the user, it’s always a good idea to generate the new key so that the application which depends on that key will not stop working, and also, it’s a good practice to notify the user.