Answers: <p>Amazon CloudTrail tracks all API use</p>
  
  <p>In CloudTrail create a new trail</p>
  
  <p><a href="https://i.sstatic.net/EEJf2.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/EEJf2.png" alt="CloudTrail Create New Trail"></a></p>
  
  <p>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</p>
  
  <p><a href="https://i.sstatic.net/NwGQe.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/NwGQe.png" alt="Send CloudTrail logs to Cloudwatch"></a></p>
  
  <p><a href="https://docs.aws.amazon.com/awscloudtrail/latest/userguide/monitor-cloudtrail-log-files-with-cloudwatch-logs.html" rel="nofollow noreferrer">https://docs.aws.amazon.com/awscloudtrail/latest/userguide/monitor-cloudtrail-log-files-with-cloudwatch-logs.html</a></p>
  
  <p>Then, run some calls on your role and wait 5 minutes.</p>
  
  <p>In Cloudwatch, go to your log trail and search for "AssumedRole". Your events will be shown here</p>
  
  <p><a href="https://i.sstatic.net/h4jE8.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/h4jE8.png" alt="enter image description here"></a></p>
  
  <p>There is also documentation on searching Cloudwatch logs with filters through the api <a href="https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/SearchDataFilterPattern.html" rel="nofollow noreferrer">https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/SearchDataFilterPattern.html</a></p>
  
Answers: CC BY-SA 4.0
Answers: 2018-12-31T10:44:26.087Z
Answers: Do you mean CloudTrail? If you mean CloudWatch, can you explain how would you go about it?
Answers: Uberhumus
Answers: CC BY-SA 4.0
Answers: 2018-12-31T21:41:21.677Z
Answers: have updated answer and linked docs
Answers: jdog
Answers: CC BY-SA 4.0
Answers: 2018-12-30T21:32:50.480Z
Answers: 2019-01-01T06:48:29.737Z
Answers: 2019-01-01T06:48:29.737Z
Answers: jdog
Answers: <p><strong>This is possible using AWS SDKs.</strong></p>
  <p>I was cleaning my tabs after finishing this task and decided I would write an answer to help other people.</p>
  <p><strong>Versions:</strong></p>
  <ul>
  <li><p>aws-cli/2.0.61</p>
  </li>
  <li><p>go1.15.3 linux/amd64</p>
  </li>
  </ul>
  <hr />
  <p>Let's do this in Golang with the right imports.</p>
  <pre><code> import (
       &quot;fmt&quot;
       &quot;github.com/aws/aws-sdk-go/aws&quot;
       &quot;context&quot;
       &quot;github.com/aws/aws-sdk-go-v2/config&quot;
       &quot;github.com/aws/aws-sdk-go-v2/service/iam&quot;
  )
  </code></pre>
  <p>First, you want to init a session and a client:</p>
  <pre><code>cfg, err := config.LoadDefaultConfig() 
  svc := iam.NewFromConfig(cfg)
  </code></pre>
  <p>Then you want to get a list of roles, to iterate through all role names. You can also use a specific role name because that's the only thing you will need to get the LastUsedDate:</p>
  <pre><code>roles_iam, err := svc.ListRoles(context.Background(), &amp;iam.ListRolesInput{
  PathPrefix: aws.String(&quot;/&quot;)})
  if err != nil {
      fmt.Println(&quot;Error&quot;, err)
      return  
  }
  
  /** For simplicity and less dereferencing: more execution speed **/
  roles_list := roles_iam.Roles    
  </code></pre>
  <p>Finally, iterate through a loop if you need to get LastUsedDate for all roles. Just set input with the right GetRoleInput arguments then call svc.GetRole to get a structure with your info.</p>
  <pre><code>/** Declare slice 'unused_roles' containing string unused role names **/
  var unused_roles []string 
  
  for i := range roles_list {
      role_name := *roles_list[i].RoleName
      input := &amp;iam.GetRoleInput{
          RoleName: aws.String(*roles_list[i].RoleName),
      }
      role_info, err := svc.GetRole(context.Background(), input)
      if err != nil {
          fmt.Println(&quot;Error&quot;, err)
      }    
        
  /** Check if role has never been used **/           
      if (role_info.Role.RoleLastUsed.LastUsedDate) == nil {
          fmt.Printf(&quot;Role %s has never been used\n&quot;, role_name)
          unused_roles = append(unused_roles, role_name)
          continue
      }
      last_used_date := *role_info.Role.RoleLastUsed.LastUsedDate
  }
  </code></pre>
  <p>More info:</p>
  <p><a href="https://docs.aws.amazon.com/IAM/latest/APIReference/API_Role.html" rel="nofollow noreferrer">https://docs.aws.amazon.com/IAM/latest/APIReference/API_Role.html</a></p>
  <p><a href="https://docs.aws.amazon.com/IAM/latest/APIReference/API_RoleLastUsed.html" rel="nofollow noreferrer">https://docs.aws.amazon.com/IAM/latest/APIReference/API_RoleLastUsed.html</a></p>
  
Answers: CC BY-SA 4.0
Answers: 2020-11-03T15:10:33.360Z
Answers: 2020-11-03T15:24:31.900Z
Answers: 2020-11-03T15:24:31.900Z
Answers: alban boitier
Answers: <p>There currently is no method using SDKs for the AWS CLI to get the last accessed time of an IAM role.</p>
  
  <p>Currently, the only way is to use the AWS Management Console.</p>
  
  <ol>
  <li>Select your <strong>IAM role</strong> and explore it</li>
  <li>Click the "<strong>Access Advisor</strong>" tab. </li>
  <li>The contents of this tab will display the last access time for each of the various services.</li>
  </ol>
  
  <p><a href="https://i.sstatic.net/Qpy7F.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/Qpy7F.png" alt="enter image description here"></a></p>
  
Answers: CC BY-SA 4.0
Answers: 2018-12-31T12:15:25.713Z
Answers: 2018-12-31T12:15:25.713Z
Answers: Subhash
Answers: <p>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.</p>
  
  <p>Specifically they recommended using 
  <code>aws iam generate-service-last-accessed-details</code> and <code>aws iam get-service-last-accessed-details-with-entities</code>, and they referred me to <a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_access-advisor-view-data.html#access_policies_access-advisor-viewing-cli" rel="nofollow noreferrer">https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_access-advisor-view-data.html#access_policies_access-advisor-viewing-cli</a>.</p>
  
  <p>For completion's sake here's how I used it:</p>
  
  <pre>#! /bin/bash
  
  ROLES=$(aws iam list-roles | jq -r .Roles[].Arn)
  for ROLE in $ROLES
  do 
      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)
      for NAMESPACE in $NAMESPACES
      do  
          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'
      done    
  done </pre>
  
Answers: CC BY-SA 4.0
Answers: 2019-02-17T14:20:40.143Z
Answers: 2019-02-17T14:20:40.143Z
Answers: Uberhumus
Body: <p>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.</p>
  
  <p>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?</p>
  
Tags: <amazon-web-services><aws-cli>
Title: How to see when an AWS IAM role was last used?
UserDisplayName: Uberhumus
ThreadText: # How to see when an AWS IAM role was last used?
  
  (Asked by: username_0 on 2018-12-30)
  
  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?
  
  **Tags:** amazon-web-services, aws-cli
  
  
  ---
  
  ## 4 answers
  
  ### Answer by username_0 on 2019-02-17. Score: 3 | Accepted 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
  do 
      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)
      for NAMESPACE in $NAMESPACES
      do  
          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'
      done    
  done 
  ```
  
  
  ---
  
  ### Answer by username_1 on 2018-12-30. Score: 5
  
  Amazon CloudTrail tracks all API use
  
  In CloudTrail create a new trail
  
  [![CloudTrail Create New Trail](https://i.sstatic.net/EEJf2.png)](https://i.sstatic.net/EEJf2.png)
  
  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](https://i.sstatic.net/NwGQe.png)](https://i.sstatic.net/NwGQe.png)
  
  <https://docs.aws.amazon.com/awscloudtrail/latest/userguide/monitor-cloudtrail-log-files-with-cloudwatch-logs.html>
  
  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](https://i.sstatic.net/h4jE8.png)](https://i.sstatic.net/h4jE8.png)
  
  There is also documentation on searching Cloudwatch logs with filters through the api <https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/SearchDataFilterPattern.html>
  
  > **Comments:**
  > **username_0**: Do you mean CloudTrail? If you mean CloudWatch, can you explain how would you go about it?  
  > **username_1**: have updated answer and linked docs  
  
  ---
  
  ### Answer by username_2 on 2020-11-03. Score: 3
  
  **This is possible using AWS SDKs.**
  
  I was cleaning my tabs after finishing this task and decided I would write an answer to help other people.
  
  **Versions:**
  
  * aws-cli/2.0.61
  * go1.15.3 linux/amd64
  
  ---
  
  Let's do this in Golang with the right imports.
  
  ```
   import (
       "fmt"
       "github.com/aws/aws-sdk-go/aws"
       "context"
       "github.com/aws/aws-sdk-go-v2/config"
       "github.com/aws/aws-sdk-go-v2/service/iam"
  )
  
  ```
  
  First, you want to init a session and a client:
  
  ```
  cfg, err := config.LoadDefaultConfig() 
  svc := iam.NewFromConfig(cfg)
  
  ```
  
  Then you want to get a list of roles, to iterate through all role names. You can also use a specific role name because that's the only thing you will need to get the LastUsedDate:
  
  ```
  roles_iam, err := svc.ListRoles(context.Background(), &iam.ListRolesInput{
  PathPrefix: aws.String("/")})
  if err != nil {
      fmt.Println("Error", err)
      return  
  }
  
  /** For simplicity and less dereferencing: more execution speed **/
  roles_list := roles_iam.Roles    
  
  ```
  
  Finally, iterate through a loop if you need to get LastUsedDate for all roles. Just set input with the right GetRoleInput arguments then call svc.GetRole to get a structure with your info.
  
  ```
  /** Declare slice 'unused_roles' containing string unused role names **/
  var unused_roles []string 
  
  for i := range roles_list {
      role_name := *roles_list[i].RoleName
      input := &iam.GetRoleInput{
          RoleName: aws.String(*roles_list[i].RoleName),
      }
      role_info, err := svc.GetRole(context.Background(), input)
      if err != nil {
          fmt.Println("Error", err)
      }    
        
  /** Check if role has never been used **/           
      if (role_info.Role.RoleLastUsed.LastUsedDate) == nil {
          fmt.Printf("Role %s has never been used\n", role_name)
          unused_roles = append(unused_roles, role_name)
          continue
      }
      last_used_date := *role_info.Role.RoleLastUsed.LastUsedDate
  }
  
  ```
  
  More info:
  
  <https://docs.aws.amazon.com/IAM/latest/APIReference/API_Role.html>
  
  <https://docs.aws.amazon.com/IAM/latest/APIReference/API_RoleLastUsed.html>
  
  
  ---
  
  ### Answer by username_3 on 2018-12-31. Score: 2
  
  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](https://i.sstatic.net/Qpy7F.png)](https://i.sstatic.net/Qpy7F.png)
  
  
  ---
  
  