0
votes

I want to create a script, and perhaps run it in a cron job every 24 hours, which will list all access keys older than 60 days.

I also want to shove the keys older than 60 days into an array so I can iterate over it and perform other options.

I'm looking at Managing access keys for IAM users - AWS Identity and Access Management and it has a aws iam get-access-key-last-used command but that's not what I want. But it's the closet thing I can find.

What I want to get the key where current date - creation date > 60 days.

I'm imagining my script would look something like this:

# some of this is pseudocode just to 
# communicate what I'm envisioning.
# I don't actually know what to put
# here yet; need assistance.

myCommand = "aws cli get key where age > 60"
staleKeys=( $( $myCommand) )

for key in "${staleKeys[@]}"
do
   # log "${key}"
   # run another aws cli command with ${key} as a value
done

Is this possible from the AWS CLI?

2
When you list access keys, each key in the response includes the CreateDate. You can infer the age.jarmod

2 Answers

3
votes

I use the following Python boto3 script, not AWS CLI.

Hope this help those who wanna use boto3:

import boto3
from datetime import datetime, timezone

def utc_to_local(utc_dt):
    return utc_dt.replace(tzinfo=timezone.utc).astimezone(tz=None)

def diff_dates(date1, date2):
    return abs(date2 - date1).days

resource = boto3.resource('iam')
client = boto3.client("iam")

KEY = 'LastUsedDate'

for user in resource.users.all():
    Metadata = client.list_access_keys(UserName=user.user_name)
    if Metadata['AccessKeyMetadata']:
        for key in user.access_keys.all():
            
            AccessId = key.access_key_id
            Status = key.status
            CreatedDate = key.create_date

            numOfDays = diff_dates(utc_to_local(datetime.utcnow()), utc_to_local(CreatedDate))
            LastUsed = client.get_access_key_last_used(AccessKeyId=AccessId)

            if (Status == "Active"):
                if KEY in LastUsed['AccessKeyLastUsed']:
                    print("User:", user.user_name,  "Key:", AccessId, "Last Used:", LastUsed['AccessKeyLastUsed'][KEY], "Age of Key:", numOfDays, "Days")
                else:
                    print("User:", user.user_name , "Key:",  AccessId, "Key is Active but NEVER USED")
            else:
                print("User:", user.user_name , "Key:",  AccessId, "Keys is InActive")
    else:
        print("User:", user.user_name , "No KEYS for this USER")
1
votes

I recommend Getting credential reports for your AWS account - AWS Identity and Access Management. This is an automated process that can generate a CSV file listing lots of information about credentials, including:

  • The date and time when the user's access key was created or last changed
  • The date and time when the user's access key was most recently used to sign an AWS API request

The report can be obtained by calling generate-credential-report, waiting a bit, then calling get-credential-report. The response needs to be base64 decoded. The result looks like this:

user,arn,user_creation_time,password_enabled,password_last_used,password_last_changed,password_next_rotation,mfa_active,access_key_1_active,access_key_1_last_rotated,access_key_1_last_used_date,access_key_1_last_used_region,access_key_1_last_used_service,access_key_2_active,access_key_2_last_rotated,access_key_2_last_used_date,access_key_2_last_used_region,access_key_2_last_used_service,cert_1_active,cert_1_last_rotated,cert_2_active,cert_2_last_rotated
user1,arn:aws:iam::111111111111:user/user1,2019-04-08T05:57:22+00:00,true,2020-05-20T10:55:03+00:00,2019-04-18T00:43:43+00:00,N/A,false,true,2019-04-08T05:57:24+00:00,2019-12-05T21:23:00+00:00,us-west-2,iot,true,2019-11-18T09:38:54+00:00,N/A,N/A,N/A,false,N/A,false,N/A

If you decide to generate the information yourself, please note that list_access_keys() only returns information about a single user. Therefore, you would need to iterate through all users, and call list_access_keys() for each user to obtain the CreationDate of the keys.

For an example of usage, see: How to scan your AWS account for old access keys using python - DEV Community