I'm working on AWS and, as part of my learning process, I create a new IAM role every time I set up a new service. I'm wondering if there's an efficient way to automatically delete IAM roles that are no longer being used. Is there some method or script that can help with this?
4 Answers
You might want to consider setting up Cloud Custodian. It's a neat tool for managing cloud resources, and it can help identify and delete unused IAM roles.
A great way to automate the removal of unused IAM roles is by using Infrastructure as Code (IaC) tools like Cloud Development Kit (CDK) or Terraform (TF). When you delete a stack, all associated resources, including IAM roles, get removed automatically. If your roles were created manually, you could write a script using the AWS SDK to loop through and delete roles based on their last usage time.
There’s a 'last activity' function on the IAM console for each role, but I’m not sure if you can access this programmatically. Knowing when a role was last used could help you determine if it's safe to delete.
Just keep in mind there’s technically no way to definitively know a role is 'unused.' It’s possible you have scripts or services using those roles without you realizing it. Roles have a last access time and a trust policy, so if a role is only allowed for Lambda, for example, you know it’s not in use elsewhere. If coding isn’t your strong suit, maybe an AI chatbot could help you draft a script. Just be cautious about trusting it entirely. If you’re willing to dive into coding, you can certainly use the boto3 SDK for programmatic access. A mixed approach, like having AI generate a listing script for review, could work too.

Related Questions
How To Get Your Domain Unblocked From Facebook
How To Find A String In a Directory of Files Using Linux