Day 18 – Rotating IAM Keys using Boto3
Welcome to Day 18 of 101 Days of DevOps. The topic for today is Rotating IAM Keys 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.
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. To notify the user, please watch the below video. Generating the new key, I will leave it as an exercise for you guys :-).
Please join me with my journey by following any of the below links
- Website: https://101daysofdevops.com/
- Twitter: @100daysofdevops OR @lakhera2015
- Facebook: https://www.facebook.com/groups/795382630808645/
- Medium: https://medium.com/@devopslearning
- GitHub: https://github.com/100daysofdevops/100daysofdevops
- YouTube Channel: https://www.youtube.com/user/laprashant/videos
- Slack: https://join.slack.com/t/100daysofdevops/shared_invite/zt-au03logz-YfDUp_FJF4rAUeDEbgWmsg
- Reddit: r/101DaysofDevops
- Meetup: https://www.meetup.com/100daysofdevops/