Saturday, 13 November 2021

Lock the user AWS account if the account is inactive for certain days

About the problem: 

 I got a specific requirement from my client compliance team that they want to disable the AWS account automatically if the user is inactive for certain days . By default AWS IAM didn't provide that option so we have to find another way to meet that compliance .

Solution :

AWS "PasswordLastUsed" api helps to check the users last time used the password . By using that I have build the below script which will disable the user if its disable for 90 days .


Lambda Script :

import datetime

import dateutil

import boto3

from dateutil import parser



UserMetaDataList = []

IAM = boto3.client('iam')

todaysDate = datetime.date.today() - datetime.timedelta(days=90) [Please change the date as per your requirement]

response=IAM.list_users(MaxItems=200)

#UserMetaDataList.extend(response['Users'])

print (response)

#print UserMetaDataList

userlen = len(response['Users'])

print (userlen)

#timeLimit=datetime.datetime.now() - datetime.timedelta(days=90)


print ("-------------------------------------------------------------")

print ("Login access Created Date" + "\t\t" + "Username")

print ("-------------------------------------------------------------")


#try:

for i in range(userlen):

    #print i

    try:

        Passwordlastused=response['Users'][i]['PasswordLastUsed']

        print (Passwordlastused)

        username=response['Users'][i]['UserName']

        print (username)

        Passwordlastused=response['Users'][i]['PasswordLastUsed']

        try:

            if(str(todaysDate)>=str(Passwordlastused)): 

                #print ( "Disableing user %s" % username")

                IAM.delete_login_profile(UserName=username)

        

        

        except Exception as e:

            print("Some error occured in lambda_handler" + '\n' + str(e))

            pass

        

    except Exception as e:

        print("Some error occured in lambda_handler" + '\n' + str(e))

        pass

        

#except Exception as e:

 #   print(e)



def lambda_handler(event, context):     

    filepath ='/tmp/volume_report.csv'

    filename ='report_Ireland' 

No comments:

Post a Comment