Search code examples
bashamazon-web-servicesamazon-iamaws-cli

Batch Delete IAM Roles from CLI Script


I'm working on cleaning up an AWS account with hundreds of unused IAM roles. Rather than delete them by selecting a few at a time from the console, I'd like to delete all that fit the criteria of their last activity being greater than 60 days ago. An example role with the list-roles AWS IAM CLI command returns the following JSON:

 {
        "Path": "/service-role/",
        "RoleName": "ExampleRoleName",
        "RoleId": "ExampleRoleID",
        "Arn": "ExampleRoleARN",
        "CreateDate": "ExampleRoleDate",
        "AssumeRolePolicyDocument": {
            "Version": "2012-10-17",
            "Statement": [
                {
                    "Effect": "Allow",
                    "Principal": {
                        "Service": "lambda.amazonaws.com"
                    },
                    "Action": "sts:AssumeRole"
                }
            ]
        },
        "MaxSessionDuration": 3600
    }

Is there a way to gather data on their last activity and use that in a script to delete roles with no activity in the last 180 days? Thanks in advance for the help.


Solution

  • Here's the basic loop in Python (IAM also supports the "resource" API, which is somewhat simpler, but this is a copy-paste-edit from code I already had):

    import boto3
    
    client = boto3.client('iam')
    
    paginator = client.get_paginator('list_roles')
    for page in paginator.paginate():
        for listed_role in page['Roles']:
            role_name = listed_role['RoleName']
            role = client.get_role(RoleName=role_name)['Role']
            last_used = role.get('RoleLastUsed', {}).get('LastUsedDate')
            print(f"{role_name}: {last_used}") 
    

    Note: when deleting a role, you first have to detach all managed policies from the role, using client.detach_role_policy().