In AWS in the GUI you can select a role and then click on delete, then when you are prompted to approve or deny the deletion it shows you when the role was last used.

I would like to be able to know when a role was last used without pretend deleting it via the GUI.Ideally if I could get that data from the AWS CLI or a Boto3 script that would be great. Is there a way to accomplish that?


Amazon CloudTrail tracks all API use

In CloudTrail create a new trail

CloudTrail Create New Trail

You can configure each trail to send log events to CloudWatch: Edit the trail and choose to send Logs to CloudWatch. It will offer you to create a Role for this

Send CloudTrail logs to Cloudwatch


Then, run some calls on your role and wait 5 minutes.

In Cloudwatch, go to your log trail and search for "AssumedRole". Your events will be shown here

enter image description here

There is also documentation on searching Cloudwatch logs with filters through the api https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/SearchDataFilterPattern.html

| improve this answer | |
  • Do you mean CloudTrail? If you mean CloudWatch, can you explain how would you go about it? – Uberhumus Dec 31 '18 at 10:44
  • have updated answer and linked docs – jdog Dec 31 '18 at 21:41

There currently is no method using SDKs for the AWS CLI to get the last accessed time of an IAM role.

Currently, the only way is to use the AWS Management Console.

  1. Select your IAM role and explore it
  2. Click the "Access Advisor" tab.
  3. The contents of this tab will display the last access time for each of the various services.

enter image description here

| improve this answer | |

I've been meaning to come back to this. After consulting with AWS support it would seem that this is possible using some functions of the AWS CLI, that I was not aware of.

Specifically they recommended using aws iam generate-service-last-accessed-details and aws iam get-service-last-accessed-details-with-entities, and they referred me to https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_access-advisor-view-data.html#access_policies_access-advisor-viewing-cli.

For completion's sake here's how I used it:

#! /bin/bash

ROLES=$(aws iam list-roles | jq -r .Roles[].Arn)
for ROLE in $ROLES
    echo $ROLE
    JOBID=$(aws iam generate-service-last-accessed-details --arn $ROLE | jq -r .JobId)
    echo $JOBID
    NAMESPACES=$(aws iam get-service-last-accessed-details --job-id $JOBID | jq -r .ServicesLastAccessed[].ServiceNamespace)
        echo $NAMESPACE
        aws iam get-service-last-accessed-details-with-entities --job-id $JOBID --service-namespace $NAMESPACE | jq '.JobCompletionDate,.EntityDetailsList[].EntityInfo.Name,.EntityDetailsList[].EntityInfo.Id'
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.