Created
June 3, 2022 14:50
-
-
Save jackton1/f08c3c9767f397a2971a8e43bd81b523 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from datetime import datetime, timedelta | |
import boto3 | |
from dateutil.tz import UTC | |
client = boto3.client('iam') | |
fifteen_days_ago = datetime.now(tz=UTC) - timedelta(days=15) | |
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') | |
if ( | |
'edgelambda.amazonaws.com' in | |
role['AssumeRolePolicyDocument']['Statement'][0]['Principal'].get("Service", []) and | |
last_used and last_used > fifteen_days_ago | |
): | |
print(f"{role_name}: {last_used}") | |
client.delete_role_policy( | |
RoleName=role_name, | |
PolicyName=f'{role_name}-policy' | |
) | |
response = client.delete_role( | |
RoleName=role_name | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment