Skip to main content

Security and hardening · Intermediate · 22 min

Review cloud IAM for unused access and old access keys

By Padding · Updated 18 Nov 2026
Python 3.15.2 (python:3.15-slim) · AWS CLI v2 · Google Cloud CLI

You will run a quarterly access review on AWS and Google Cloud, using a small Python script to flag access keys over 90 days old and console users without MFA, and finish with a decision and an owner for every finding.

On this page

Cloud accounts collect access the way a kitchen drawer collects keys. A contractor leaves and their login stays. A deploy job gets an access key in 2025 and nobody rotates it. A role created for a one-off migration still has write access to every bucket. None of it shows up as an error, so it stays until someone looks, or until someone else finds it first.

This tutorial is that look, done as a repeatable review you can run every quarter. It is not a guide to setting IAM up: understand AWS IAM users, groups and roles and grant least privilege access in Google Cloud IAM cover that. Here you will:

  • download the AWS credential report and flag old keys, unused credentials and missing MFA with a Python script you write
  • check what a flagged identity really uses with last accessed data and IAM Access Analyzer
  • do the same review on Google Cloud with the IAM recommender and service account key usage
  • decide what happens to each finding, and record the few you accept with an owner and an end date

The script runs on a sample report first, so you can see every kind of finding before you point it at a real account. The account ID 111122223333 and all the names in it are made up.

Step 1 · Download the AWS credential report

The credential report is a CSV file with one row per IAM user, plus one for the root user. For each it gives the creation date, whether a console password exists and when it was last used, whether MFA is on, and the age and last use of the user's first two access keys. IAM keeps one report and builds a new one at most every four hours.

Make a folder for the review. The report lists every user and key age in the account, so create files in it private from the start with umask 077:

Bash
mkdir -p ~/iam-review-demo
cd ~/iam-review-demo
umask 077

Ask IAM to build the report, then download it. get-credential-report returns the file base64-encoded, so decode it on the way to disk. Run the first command again until it prints "State": "COMPLETE":

Bash
aws iam generate-credential-report
aws iam get-credential-report --query Content --output text | base64 --decode > credential-report.csv

In the console the same file is under IAM, Credential report, Download report. It is a few kilobytes even for a large account, so it downloads quickly on a metered mobile connection, and everything after this point runs offline.

For practice, create a sample report with the same columns instead. It has seven rows: the root user, three people and three machine users:

Bash
cat > sample-report.csv <<'CSV'
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,additional_credentials_info
<root_account>,arn:aws:iam::111122223333:root,2023-01-09T08:00:00+00:00,not_supported,2026-11-02T07:41:10+00:00,not_supported,not_supported,true,false,N/A,N/A,N/A,N/A,false,N/A,N/A,N/A,N/A,false,N/A,false,N/A,
amara.okafor,arn:aws:iam::111122223333:user/amara.okafor,2024-02-12T10:15:00+00:00,true,2026-11-25T08:02:44+00:00,2026-06-01T09:00:00+00:00,N/A,true,true,2026-10-02T11:20:00+00:00,2026-11-25T08:10:00+00:00,eu-west-1,s3,false,N/A,N/A,N/A,N/A,false,N/A,false,N/A,
ci-deploy,arn:aws:iam::111122223333:user/ci-deploy,2025-03-14T16:40:00+00:00,false,N/A,N/A,N/A,false,true,2025-03-14T16:41:00+00:00,2026-11-25T22:15:00+00:00,af-south-1,ecr,false,N/A,N/A,N/A,N/A,false,N/A,false,N/A,
kwame.mensah,arn:aws:iam::111122223333:user/kwame.mensah,2025-09-03T07:30:00+00:00,true,2026-11-20T13:05:12+00:00,2025-09-03T07:30:00+00:00,N/A,false,false,N/A,N/A,N/A,N/A,false,N/A,N/A,N/A,N/A,false,N/A,false,N/A,
old-backup,arn:aws:iam::111122223333:user/old-backup,2024-06-01T09:00:00+00:00,false,N/A,N/A,N/A,false,true,2024-06-01T09:02:00+00:00,2025-01-10T02:00:00+00:00,eu-west-1,s3,false,N/A,N/A,N/A,N/A,false,N/A,false,N/A,
reporting-bot,arn:aws:iam::111122223333:user/reporting-bot,2026-07-15T12:00:00+00:00,false,N/A,N/A,N/A,false,true,2026-07-15T12:01:00+00:00,N/A,N/A,N/A,false,N/A,N/A,N/A,N/A,false,N/A,false,N/A,
thandiwe.dube,arn:aws:iam::111122223333:user/thandiwe.dube,2025-01-20T09:00:00+00:00,true,2026-05-02T15:30:00+00:00,2025-01-20T09:00:00+00:00,N/A,true,false,N/A,N/A,N/A,N/A,false,N/A,N/A,N/A,N/A,false,N/A,false,N/A,
CSV

Check it worked

Bash
python3 -c "import csv; rows = list(csv.DictReader(open('sample-report.csv'))); print(len(rows), 'rows'); print(rows[2]['user'], rows[2]['access_key_1_last_rotated'])"

The output is 7 rows, then ci-deploy 2025-03-14T16:41:00+00:00. A real report has the same header line. If yours opens in a spreadsheet with everything in one column, the file is still base64: decode it as shown above.

Step 2 · Write the review script

The report is easy to read for ten users and tiring for a hundred, and a person skimming a spreadsheet misses rows. The script below applies the same rules to every row. With a 90 day limit by default it flags:

  • OLD_KEY: an active access key created or last rotated more than 90 days ago
  • UNUSED_KEY: an active key never used, or not used for more than 90 days
  • NO_MFA: a user with a console password and no MFA device
  • UNUSED_PASSWORD: a console password not used for more than 90 days (or never used, counted from the user's creation date)
  • ROOT_KEY and ROOT_NO_MFA: an access key on the root user, or a root user without MFA

It also reads an optional exceptions file, which you will fill in later. Save it as audit.py. It uses only the standard library, so there is nothing to install:

Bash
cat > audit.py <<'PY'
"""Flag old access keys, unused credentials and missing MFA in an AWS credential report."""

import argparse
import csv
from datetime import date, datetime

EMPTY = {"", "N/A", "no_information", "not_supported"}


def day(value):
    """Turn an ISO 8601 timestamp into a date, or None for the report's empty markers."""
    value = value.strip()
    if value in EMPTY:
        return None
    return datetime.fromisoformat(value).date()


def yes(value):
    return value.strip().lower() == "true"


def check_user(row, today, max_age):
    """Yield (check, detail) pairs for one row of the report."""
    root = row["user"] == "<root_account>"
    created = day(row["user_creation_time"])

    if root and not yes(row["mfa_active"]):
        yield "ROOT_NO_MFA", "the root user has no MFA device"
    if not root and yes(row["password_enabled"]):
        if not yes(row["mfa_active"]):
            yield "NO_MFA", "console password without MFA"
        last = day(row["password_last_used"]) or created
        if (today - last).days > max_age:
            yield "UNUSED_PASSWORD", f"password not used for {(today - last).days} days"

    for n in ("1", "2"):
        if not yes(row[f"access_key_{n}_active"]):
            continue
        if root:
            yield "ROOT_KEY", f"the root user has active access key {n}"
        age = (today - day(row[f"access_key_{n}_last_rotated"])).days
        if age > max_age:
            yield "OLD_KEY", f"access key {n} is {age} days old"
        used = day(row[f"access_key_{n}_last_used_date"])
        if used is None:
            yield "UNUSED_KEY", f"access key {n} has never been used"
        elif (today - used).days > max_age:
            yield "UNUSED_KEY", f"access key {n} last used {(today - used).days} days ago"


def load_exceptions(path):
    """Read user,check,expires,owner,reason rows into a dict keyed by (user, check)."""
    if not path:
        return {}
    with open(path, newline="", encoding="utf-8") as f:
        return {(r["user"], r["check"]): r for r in csv.DictReader(f)}


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("report", help="credential report CSV")
    parser.add_argument("--max-age", type=int, default=90, help="days (default 90)")
    parser.add_argument("--today", type=date.fromisoformat, default=date.today(),
                        help="date to measure from, YYYY-MM-DD (default: today)")
    parser.add_argument("--exceptions", help="CSV of accepted risks with an expiry date")
    args = parser.parse_args()

    exceptions = load_exceptions(args.exceptions)
    findings, accepted = [], 0
    with open(args.report, newline="", encoding="utf-8") as f:
        for row in csv.DictReader(f):
            for check, detail in check_user(row, args.today, args.max_age):
                ex = exceptions.get((row["user"], check))
                if ex and date.fromisoformat(ex["expires"]) >= args.today:
                    accepted += 1
                    continue
                if ex:
                    findings.append(("EXPIRED_EXCEPTION", row["user"],
                                     f"{check} exception ended {ex['expires']} ({ex['owner']})"))
                findings.append((check, row["user"], detail))

    for check, user, detail in findings:
        print(f"{check:<18} {user:<15} {detail}")
    print(f"{len(findings)} findings, {accepted} accepted as exceptions")


if __name__ == "__main__":
    main()
PY

The report marks missing values with N/A, no_information or not_supported, and day() turns all three into None. Timestamps are ISO 8601 with an offset, which datetime.fromisoformat reads directly. The --today option lets you rerun an old review and get the same answers.

Check it worked

Bash
python3 audit.py --help

The help lists report, --max-age, --today and --exceptions. A SyntaxError here means part of the file was lost in the paste: create it again.

Step 3 · Run it on the sample report

The sample was written for 26 November 2026, so pass that date to get the output shown here:

Bash
python3 audit.py sample-report.csv --today 2026-11-26

The output is:

Text
OLD_KEY            ci-deploy       access key 1 is 622 days old
NO_MFA             kwame.mensah    console password without MFA
OLD_KEY            old-backup      access key 1 is 908 days old
UNUSED_KEY         old-backup      access key 1 last used 685 days ago
OLD_KEY            reporting-bot   access key 1 is 134 days old
UNUSED_KEY         reporting-bot   access key 1 has never been used
UNUSED_PASSWORD    thandiwe.dube   password not used for 208 days
7 findings, 0 accepted as exceptions

Read the findings as questions, not verdicts. ci-deploy has an old key that was used yesterday, so something depends on it. old-backup has a key nobody has used for almost two years, which is the safest kind of finding to remove. amara.okafor does not appear: her password is in use, she has MFA, and her key is 55 days old.

Ninety days is a common limit, not a law. Try a stricter one to see how the list changes:

Bash
python3 audit.py sample-report.csv --today 2026-11-26 --max-age 30

Check it worked

The 30 day run prints 8 findings, 0 accepted as exceptions, with one new line: OLD_KEY for amara.okafor, whose key is 55 days old. Pick one limit for your organisation, write it in the review record and keep it the same each quarter, or the trend from one review to the next means nothing.

Step 4 · Check the root user rules

The sample's root user is in good shape, so the two root checks have not fired yet. A key on the root user is the worst finding a review can turn up: IAM policies cannot restrict the root user, so that key can do almost anything in the account. Build a one-row report to prove the script catches it. head -1 copies the header line from the sample:

Bash
head -1 sample-report.csv > root-test.csv
cat >> root-test.csv <<'CSV'
<root_account>,arn:aws:iam::111122223333:root,2023-01-09T08:00:00+00:00,not_supported,2026-11-02T07:41:10+00:00,not_supported,not_supported,false,true,2023-01-09T08:05:00+00:00,2026-11-24T10:00:00+00:00,us-east-1,iam,false,N/A,N/A,N/A,N/A,false,N/A,false,N/A,
CSV
python3 audit.py root-test.csv --today 2026-11-26

Check it worked

The output has three findings for <root_account>: ROOT_NO_MFA, ROOT_KEY and OLD_KEY (1417 days old). If a real report ever shows ROOT_KEY, deal with it the same day: sign in as root with MFA, check CloudTrail for what the key has done, and delete it.

Step 5 · See what flagged identities really use on AWS

The credential report says when a key was last used, not what it was used for. Before you remove or narrow anything, find out what the identity touches, so you replace exactly that and nothing more.

Last accessed data lists, for a user, group, role or policy, each service it is allowed to use and when it last used it. It is a job you start and then read. Replace the ARN with one from your own report, and paste the JobId the first command prints into the second:

Bash
aws iam generate-service-last-accessed-details --arn arn:aws:iam::111122223333:user/ci-deploy
aws iam get-service-last-accessed-details --job-id <job-id>

The second command shows each service with a LastAuthenticated date, or none if it was never used. For ci-deploy you might find it pushes to ECR and nothing else, even though its policy allows S3 and EC2 too. That list is the policy of the role that will replace it.

IAM Access Analyzer unused access does the same work continuously, across users and roles, and the credential report cannot see roles at all. It reports unused roles, unused user access keys and passwords, and unused permissions on roles. Unlike the free external access analyzer, it is charged per IAM role and user analysed each month, so check the current price on the AWS pricing page before you create one. Create it with your review limit, then list what it finds:

Bash
aws accessanalyzer create-analyzer --analyzer-name unused-access-90d --type ACCOUNT_UNUSED_ACCESS --configuration '{"unusedAccess":{"unusedAccessAge":90}}'
aws accessanalyzer list-findings-v2 --analyzer-arn <analyzer-arn> --filter '{"status":{"eq":["ACTIVE"]}}'

The first command prints the analyzer's ARN; use it in the second. The first scan can take a while. If you only want it for this review, delete it when you are done so it stops billing:

Bash
aws accessanalyzer delete-analyzer --analyzer-name unused-access-90d

Check it worked

You have, for each finding from your own report, a short note of what that identity used in the last 90 days, for example ci-deploy: ecr only, daily or old-backup: nothing since January 2025. Access Analyzer's list should include the same unused keys your script flagged, plus any unused roles, which the script cannot see.

Step 6 · Run the same review on Google Cloud

Google Cloud has no credential report, but two tools answer the same questions.

The IAM recommender looks at the permissions each principal used over the last 90 days and suggests removing roles nobody uses or swapping a broad role for a narrower one. Replace <project-id> with yours:

Bash
gcloud recommender recommendations list --location=global --recommender=google.iam.policy.Recommender --project=<project-id> --format=json

Each recommendation names the member, the role and what to change, such as a REMOVE_ROLE subtype for a role with no recent use. Treat these the way you treated the AWS findings: check with the owner, then act.

Service account keys are Google Cloud's long-lived access keys and carry the same risk. List the keys you or your team created for a service account (keys Google manages itself are left out), then ask when each key last signed in:

Bash
gcloud iam service-accounts keys list --iam-account=<service-account-email> --managed-by=user
gcloud policy-intelligence query-activity --activity-type=serviceAccountKeyLastAuthentication --project=<project-id>

The second command needs the Policy Analyzer API and the Activity Analysis Viewer role, and Google lists it as Pre-GA. Read its output with care: the time is always shown as 07:00:00Z whatever time the key was really used, very recent use may be missing, disabled keys are left out, and a key that has never been used has no lastAuthenticatedTime at all.

Check it worked

Your review notes now have a Google Cloud section, listing each user-managed key with its creation date and last authentication date, and each recommender suggestion with the person who owns that access.

Step 7 · Decide what happens to each finding

Every finding ends in one of four decisions. Write the decision next to the finding before you change anything, so a mistake can be traced back.

Remove credentials nobody uses. Deactivate first and delete later: a deactivated key can be switched back on in seconds if something breaks, a deleted one cannot. Removing a key or login stops whatever uses it at once, so confirm the last-use date before each command. Replace the user names and key IDs with your own:

Bash
aws iam list-access-keys --user-name old-backup
aws iam update-access-key --user-name old-backup --access-key-id <access-key-id> --status Inactive

After a quiet week or two, delete it with aws iam delete-access-key --user-name old-backup --access-key-id <access-key-id>. For someone who has left, like thandiwe.dube, remove the console password with aws iam delete-login-profile --user-name thandiwe.dube, then the user. On Google Cloud, gcloud iam service-accounts keys disable <key-id> --iam-account=<service-account-email> is the deactivate step.

Replace long-lived keys that are in use with short-lived credentials. A CI job like ci-deploy should assume a role through OIDC instead of holding a key: deploy to AWS from GitHub Actions with OIDC and authenticate GitHub Actions to Google Cloud with Workload Identity walk through it. Code on EC2, ECS or Lambda should use the role the service provides. People should sign in through IAM Identity Center or your identity provider, where MFA is set once, instead of having IAM users. If a key has to stay for now, rotate it: create the second key, switch the app, deactivate the old one, delete it.

Shorten what stays. A role's maximum session can be anything from one to twelve hours. One hour is plenty for most people and jobs:

Bash
aws iam update-role --role-name <role-name> --max-session-duration 3600

Accept a finding for a fixed time, with a named owner and a reason, when the fix needs work that cannot happen this week. That is what the exceptions file is for. Record two: ci-deploy's old key until the OIDC move lands, and a reporting-bot exception that has already run out, so you can see what the script does with it:

Bash
cat > exceptions.csv <<'CSV'
user,check,expires,owner,reason
ci-deploy,OLD_KEY,2026-12-31,amara.okafor,Moving the deploy job to an OIDC role; key deleted after cut-over
reporting-bot,UNUSED_KEY,2026-10-31,kwame.mensah,Waiting for the reporting job to go live
CSV
python3 audit.py sample-report.csv --today 2026-11-26 --exceptions exceptions.csv

Check it worked

The ci-deploy line is gone and the summary reads 7 findings, 1 accepted as exceptions. A new line, EXPIRED_EXCEPTION reporting-bot UNUSED_KEY exception ended 2026-10-31 (kwame.mensah), sits above the unused key it was covering. An exception that runs out comes back as a finding with its owner named, so nothing is accepted for ever by accident. Every finding still on the list now has a decision written next to it.

Step 8 · Save the review and book the next one

Save the output with the date in the file name. Next quarter, compare the two: the number of findings should fall, and anything that appears twice needs a harder conversation with its owner.

Bash
python3 audit.py sample-report.csv --today 2026-11-26 --exceptions exceptions.csv > review-2026-11-26.txt
ls -l review-2026-11-26.txt

Keep the review file, exceptions.csv and audit.py together in a private repository or your team's restricted shared drive. They describe weak points in your account, so treat them like any other sensitive record, and never commit the raw credential report. Put the next review in the calendar now, three months out, with the same 90 day limit.

Check it worked

ls -l shows review-2026-11-26.txt with -rw------- permissions, readable only by you because of the umask 077 from the first step. Running tail -1 review-2026-11-26.txt prints 7 findings, 1 accepted as exceptions.

When you have finished practising, remove the demo folder. If you created the Access Analyzer only for this review, make sure you deleted it as shown above.

Bash
cd ~
rm -rf ~/iam-review-demo

Next steps

Need this done for you?

Padding does this work for growing companies, from the first diagnosis to a system that keeps working.

Operational and Technology Management

Get new tutorials

New tutorials, about twice a month.