Skip to main content

List all AWS IAM roles with their last used date

The following Python script will help to list all the AWS IAM roles with the last used date. If the role is not been used, it will show 'Never used" instead of date. You will require Python3.8 or above to run the script.

I prefer to use Tabulate to format the output in to table format. You can format the output in to HTML or even convert in to CSV file too.

Let's start the script to list all IAM role and its last used date.

import boto3
import time
from tabulate import tabulate

Once you've imported the boto3, time and tabulate module, let's setup the AWS session using the AWS config profile and region name.

session = boto3.Session(profile_name=profile, region_name=region)

iam_client = session.client('iam')

# use paginator if you have long list of IAM roles

paginator = iam_client.get_paginator('list_roles')
iterator = paginator.paginate()

The following lines will help to setup the header row of the table in the output. In this example, I am only printing IAM role name and last used date. You can add other attributes like Role Id, Arn, created date, AssumeRolePolicyDocument and action.

pending_request = []
pending_request.append(['IAM Role Name', 'Last used date'])

Here is the main block of code where script will run in to loops to get the Roles information. From the Roles information, it will extract the RoleName. Once you've role name, it will fetch the role information like Role Id, Arn, created date, AssumeRolePolicyDocument, action and last used date.

# Looping though Roles to get Role names

for page in iterator:
    for role_names in page['Roles']:
        role_name = role_names['RoleName']

        # Getting Role related data      

        get_roles = iam_client.get_role(
          RoleName=role_name
        )  
       
        reply = get_roles['Role']
        last_used = reply['RoleLastUsed']
       
        try:
            # Getting last used date of the role

            last_used_date = last_used['LastUsedDate']

            # print the role name and last used date

            if last_used_date != '':
                print_response = [reply['RoleName'], last_used['LastUsedDate'].strftime("%d/%m/%Y %H:%M:%S")]
                pending_request.append(print_response)
           
        except Exception as e:
            # print role name and 'Never used' if there is no last date available

            print_response = [reply['RoleName'], 'Never used']
            pending_request.append(print_response)
            continue

# Printing the putput

print(tabulate(pending_request, headers="firstrow",tablefmt='simple'))

You can format the way date and time shown in the output by modifying the values in .strftime("%d/%m/%Y %H:%M:%S").

Hope you find it useful.

Disclaimer: www.TechieTalks.co.uk does not conceal the possibility of error and shortcomings due to human or technical factors. www.TechieTalks.co.uk does not bear responsibility upon any loss or damage arising from conduct or activities related to the use of data and information contained in this blog.


Comments

Popular posts from this blog

Windows 10 phone: This device has been locked for security reasons. Connect your device to a power source for at least two hours, then restart it to try again.

Hi All, this is my very first post on Windows 10 phone. I have a Windows 10 phone. Today, I saw following error message on phone. It didn’t allow me to unlock my phone using 4 digit pin I had set. The “Emergency calls” was the only option available to me. Error: This device has been locked for security reasons. Connect your device to a power source for at least two hours, then restart it to try again. I tried performing soft reboot but it didn’t fix. After doing a bit of research, I found a solution. Make sure that your phone is connected to Internet during this process. To fix this issue, follow these steps: Launch https://account.microsoft.com/devices on a web browser on another PC/Tablet or a smart phone Login using your Microsoft account (it is the same account you’ve used to configure your phone). Once you’ve logged in, Select your phone. On the next page, click on Lock button. A box will appear asking to enter 6 digit pin , a number where you can be reached (op

Fixed: HTC One M8 USB driver doesn’t recognized by Windows 10

Hi friends, recently I upgraded my Windows 7 OS to Windows 10 on my laptop. Everything was working fine until I plugged my HTC One M8 (Android) phone to laptop using USB cable. A message box appeared stating that it could not detect the USB device. I never had any problem when I was using Windows 7. I used to plug my phone to PC using USB cable and access phone storage as USB drive. I typed my query in google and most of the articles suggested that I should installed HTC Sync Manager and then connect my phone. Well, I installed the required application but it did not resolve the issue. Hence, I removed it. This is my 3 rd HTC phone and I started to find out how I can enable USB debugging mode on my phone. This option is hidden by default. To enable this option, follow these steps:  Go to Settings \ About Select Software Information Click on More  option Now, tap on Build number  option six times in a row. A message will be shown saying “ You are now a developer! ” Go

Virtual USB port is missing on Windows 7

Hi All, it has been a long time since I have posted last blog. I was away for a while during Christmas time. Today, I am going to share information about how to get virtual USB port in drop down list while installing local printer (USB) on Windows 7, if it’s not available by default. I followed below steps to add virtual USB port to add USB printer to Windows 7 PC.           Click on Start . Go to Devices and Printers .           Click on Add Printer .           Select Add a local Printer           In Choose a printer port box, select Create a new port option.           From the drop down list, choose Local port and click on Next button.           Port Name dialog box will appear. Type port name USB001 , click on OK           In the step, choose appropriate printer driver from list or provide a driver disk to complete printer driver installation process. I hope you may find this very useful. Disclaimer: www.TechieTalks.co.uk does not conceal the possibility of