About Me

My photo
Pune, maharashtra, India

Tuesday, February 1, 2022

Delete All IAM Roles in AWS Account

Term : 

  • IAM -Identity and Access Management 

IAM Roles :

IAM stands for identity and access management. we use it for providing access to 

service. There are some cases when sometimes we create IAM roles on AWS 

accounts and we forget to delete them. Deleting these IAM roles manually is a 

very difficult task. With the help of automation, we can delete those roles on our 

AWS account. 


Note: Please do not use it in production.

Prerequisite: 

AWS CLI : 

AWS CLI is a command-line tool for managing AWS accounts. We can create, update 

and delete resources using AWS CLI.

Boto3 :

Boto3 is a python library for creating and running python scripts. Boto3 strongly 

support AWS CLI so we can create, update and delete AWS resources using Boto3

Steps for deleting all IAM roles on AWS account :

Step 1 :  

Export profile in your local terminal using the command below :


>> export AWS_PROFILE=<your_profile_name>

Step 2 :

Create delete_all_roles.py file in your directory, and paste the below code in the 

directory.


import boto3


client = boto3.client('iam')

response = client.list_roles()


for role_info in response['Roles']:

    try:

        delete_response = client.delete_role(RoleName=role_info['RoleName'])

        print("Deleting   :-   "+role_info['RoleName'])

    except:

        print("System defined role can't delete "+role_info['RoleName'])

Step 3 :

Run that python file using the command below:

       

>> python delete_all_roles.py

Conclusion :

Just take a small coffee break and wait for some time one by one all roles on the AWS 

account will be deleted. After successfully completing all execution you can see a 

list of deleted roles and system-defined roles that are not to be deleted. In that way, 

your account will clean up.



Please feel free to comment and ask questions, I will definitely help you 


2 comments: