Untitled

 avatar
unknown
plain_text
a year ago
2.2 kB
4
Indexable
#####################Delete IAM roles + logging ##########################
import boto3
import csv
import logging

# Configure logging to output to a file
logging.basicConfig(
    filename='iam_role_deletion.log',  # Log file name
    level=logging.INFO,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger(__name__)

# Function to delete an IAM role
def delete_iam_role(role_name):
    iam_client = boto3.client('iam')

    try:
        # Detach all policies attached to the role
        attached_policies = iam_client.list_attached_role_policies(RoleName=role_name)['AttachedPolicies']
        for policy in attached_policies:
            iam_client.detach_role_policy(RoleName=role_name, PolicyArn=policy['PolicyArn'])
            logger.info(f"Detached policy '{policy['PolicyArn']}' from role '{role_name}'.")

        # Delete inline policies attached to the role
        inline_policies = iam_client.list_role_policies(RoleName=role_name)['PolicyNames']
        for policy_name in inline_policies:
            iam_client.delete_role_policy(RoleName=role_name, PolicyName=policy_name)
            logger.info(f"Deleted inline policy '{policy_name}' from role '{role_name}'.")

        # Delete the IAM role
        iam_client.delete_role(RoleName=role_name)
        logger.info(f"Deleted IAM role '{role_name}'.")
    except iam_client.exceptions.NoSuchEntityException:
        logger.error(f"IAM role '{role_name}' not found. It may have already been deleted.")
    except Exception as e:
        logger.error(f"Failed to delete role '{role_name}': {str(e)}")

# Function to read roles from CSV file
def read_roles_from_csv(csv_file):
    roles = []

    with open(csv_file, mode='r') as file:
        reader = csv.reader(file)
        for row in reader:
            roles.append(row[0])  # Assuming role names are in the first column

    return roles

# Example usage:
def main():
    csv_file_path = 'deleteroles.csv'  # Path to your CSV file

    roles = read_roles_from_csv(csv_file_path)

    for role_name in roles:
        delete_iam_role(role_name)

if __name__ == "__main__":
    main()
Editor is loading...
Leave a Comment