from datetime import datetime import json import boto3 import csv from dateutil.relativedelta import relativedelta client = boto3.client('iam') config_client = boto3.client('config') with open('policies.csv', 'w') as csvfile: writer = csv.DictWriter(csvfile, fieldnames=[ 'Name', 'Arn', 'AttachmentCount', 'CreateDate', 'UpdateDate', 'DateLastAttached', 'AttachedGroups', 'AttachedUsers', 'AttachedRoles', 'Tags', ]) writer.writeheader() for list_policies_page in client.get_paginator('list_policies').paginate(Scope='Local'): for policy in list_policies_page['Policies']: try: print(f'processing policy {policy["PolicyName"]}') policy = client.get_policy(PolicyArn=policy['Arn'])['Policy'] attached_groups = [] attached_users = [] attached_roles = [] date_last_attached = '' if policy['AttachmentCount'] > 0: for entities_page in client.get_paginator('list_entities_for_policy').paginate(PolicyArn=policy['Arn']): attached_groups = [group['GroupName'] for group in entities_page.get('PolicyGroups', [])] attached_users = [user['UserName'] for user in entities_page.get('PolicyUsers', [])] attached_roles = [role['RoleName'] for role in entities_page.get('PolicyRoles', [])] else: for config_history_page in config_client.get_paginator('get_resource_config_history').paginate( resourceType='AWS::IAM::Policy', resourceId=policy['PolicyId'], earlierTime=(datetime.now() - relativedelta(years=1)) ): if date_last_attached: break for item in config_history_page['configurationItems']: configuration = json.loads(item['configuration']) if configuration['attachmentCount'] > 0: date_last_attached = item_configuration_time break item_configuration_time = item['configurationItemCaptureTime'] writer.writerow({ 'Name': policy['PolicyName'], 'Arn': policy['Arn'], 'AttachmentCount': policy['AttachmentCount'], 'CreateDate': policy['CreateDate'].strftime("%Y-%m-%d %H:%M:%S"), 'UpdateDate': policy['UpdateDate'].strftime("%Y-%m-%d %H:%M:%S"), 'DateLastAttached': date_last_attached.strftime("%Y-%m-%d %H:%M:%S") if date_last_attached else '', 'AttachedGroups': '\n'.join(attached_groups), 'AttachedUsers': '\n'.join(attached_users), 'AttachedRoles': '\n'.join(attached_roles), 'Tags': ','.join([f'{tag["Key"]}={tag["Value"]}' for tag in policy['Tags']]) }) except Exception as e: print(f'Exception processing policy {policy["PolicyName"]}: {e}')