简体   繁体   中英

How do we fetch IAM service last accessed details using Boto3?

Below is my code before converting to report\\csv format

client=boto3.client('iam',aws_access_key_id='somedeclaredvariable',aws_secret_access_key='somedeclaredvariable')

users=client.list_users()

for x in users['Users']:

    response = client.generate_service_last_accessed_details(Arn=x['Arn'],Granularity='SERVICE_LEVEL')
    response1=client.get_service_last_accessed_details(JobId=response['JobId'])
    if(response1['JobStatus']!='IN_PROGRESS'):
        print(response1['ServicesLastAccessed'])

Output i get doesnt have any data in ServicesLastAccessed list

It is simply an empty list : []

I run your same code in AWS Lambda

import json
import boto3

def lambda_handler(event, context):
    # TODO implement
    client=boto3.client('iam')

    users=client.list_users()
    print(users)
    
    for x in users['Users']:
    
        response = client.generate_service_last_accessed_details(Arn=x['Arn'],Granularity='SERVICE_LEVEL')
        print(response)
        response1=client.get_service_last_accessed_details(JobId=response['JobId'])
        if(response1['JobStatus']!='IN_PROGRESS'):
            print(response1['ServicesLastAccessed'])

generate_service_last_accessed_details(**kwargs)

Generates a report that includes details about when an IAM resource (user, group, role, or policy) was last used in an attempt to access AWS services. Recent activity usually appears within four hours.

I was also not getting result for GenerateServiceLastAccessedDetails this. But i tried running another Lambda which used same user role. Not this got access after this am able to get result.

{'JobId': 'XXXXX', 'ResponseMetadata': {'RequestId': 'bac90379-dXXXXX', 'HTTPStatusCode': 200, 'HTTPHeaders': {'x-amzn-requestid': 'bac90XXXX', 'content-type': 'text/xml', 'content-length': '395', 'date': 'Thu, 15 Oct 2020 06:40:29 GMT'}, 'RetryAttempts': 0}}

Clearly said get_service_last_accessed_details(**kwargs) Retrieves a service last accessed report that was created using the GenerateServiceLastAccessedDetails operation. Note :

  • Make sure you have right access for IAM role which going to get user details
  • Its give last four hours activities. Tried accessing now and then run this code.

I found you have to poll on the result from get_service_last_accessed_details(JobId=) until you get a JobStatus of COMPLETED.

I put in a series of waits to cover the quick response cases, and the slower ones, eg.

for job_wait in (0.1, 0.1, 0.2, 0.4, 0.5, 1.0, 1.0):
  response = ...
  status = response.get('JobStatus', '')
  if status == 'COMPLETED':
  .... exit with result
  time.sleep(job_wait)
else:
  # loop completed without getting a result

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM