How to delete users from AWS using Boto3

Programmers working on computer program
Reading Time: 2 minutes

Content

Hi all, in some cases of automation we need to have a python script which will be executing every hour or once in a day(according to the requirement) which will be deleting user from AWS console. Users will be creating their account using your platform but deleting them will be our’s responsibility. We will be using boto3 which is a aws(amazon web service) software development kit for python.

In order to delete a user we must:-
1. Delete login profile of user if it exists
2. Detach user policy from user
3. Delete access keys
4. Finally delete the user

Here i will be deleting users(except the root/admin who has administrator access) who exist for more than an hour. you can change the timing according to your use case.

For this i need to retrieve all the user name from AWS which exist for more than half an hour. I will be writing python script for this using boto3.

import boto3
import datetime
iam = boto3.client('iam')
user_name=[]

def timeDiff(create_time, current_time):
    running_time = current_time - create_time
    return running_time.seconds/60


for user in iam.list_users()['Users']:
    print(user["UserName"])
    time=timeDiff(user['CreateDate'], datetime.datetime.now(user['CreateDate'].tzinfo))
    print(time)
    if time>60 and user['UserName']!='Admin':    #change the name Admin to        #the user who got administrative access
        user_name.append(user['UserName'])
    
print(user_name)

Here, i am importing boto3 and datetime. We have an empty list user_name. timeDiff function is returning the time from how long the user is active. If that is greater than 30 min then appending it into the user_name list.

Deleting login profile of the user:-

############## 1. Delete Login Profile of user #######################
for user in user_name:
    iam.delete_login_profile(UserName=user)
###################################################################



Detach policy from user(you have to provide the arn of policy):-

############### 2. Dettach policy from user  #############
iam= boto3.resource('iam')
for user in user_name:
    user1 = iam.User(user)
    user1.detach_policy(PolicyArn='arn:aws:iam::572163513905:policy/ec2-readonly-2')

#############################################################################

Retrieve and delete Access key id:-

############## 3. Retrieve and Delete Access Key ID ###############
iam = boto3.client('iam')

paginator = iam.get_paginator('list_access_keys')
for user in user_name:
    for response in paginator.paginate(UserName=user):
        access_id=response['AccessKeyMetadata'][0]['AccessKeyId']
        iam.delete_access_key(AccessKeyId=access_id, UserName=user)

Delete the users:-

########################### 4. Delete users ######################

for user in user_name:
    iam.delete_user(UserName=user)

#############################################################################

 

For more details regarding aws s3 please visit:- https://aws.amazon.com/s3/
For integrating terraform with s3 please visit:- https://blog.knoldus.com/how-to-create-s3-bucket-in-aws-using-terraform/

Conclusion

In this blog we have seen how to delete users from aws console using boto3 script. We have to follow 4 steps in order to do the same. 1.Delete login profile of user if it exists 2.Detach user policy from user 3.Delete access keys 4.Finally delete the user. We have also seen the detailed script of boto3 and understood the concept about the same. We can now understand that we can automate variety of things using python. This was just one example


Leave a Reply