devops

Build a Credential Rotation Agent: Find IAM Access Keys Older Than 90 Days and Secrets Manager Secrets That Never Rotate, Prove Who Still Uses Them, and Rotate Without an Outage

Build a credential rotation agent: find stale IAM access keys and Secrets Manager secrets with rotation off, map every consumer, and rotate without an outage.

November 23, 2026·13 min read·
#ai#security#aws#devops#automation#kubernetes#terraform

What This Agent Does

A credential rotation agent inventories every long-lived credential in your AWS accounts (IAM user access keys, Secrets Manager secrets, and the Kubernetes Secrets synced from them), works out how old each one is, finds out who still uses it, and gives each a verdict: delete it, replace it with a role, rotate it now, turn on scheduled rotation, or fix the consumer first. Rotation config ships as a Terraform pull request. The only direct write it can make is setting an access key to Inactive, which is reversible, and that sits behind an approval.

The reason this needs an agent and not a compliance scanner is that finding old keys is the easy tenth of the job. Every scanner will tell you svc-report-uploader has a key from 2023. None of them will tell you which cron job on which host still signs requests with it, and that missing fact is why the ticket has been open for a year. People do not skip rotation out of laziness. They skip it because the last rotation broke something nobody knew was attached.

This is the scheduled-hygiene sibling of the secret leak triage agent. That one reacts to a credential that is already exposed. This one shortens how long any credential lives, so that the next leak is of something already dead.

Step 1: Inventory Access Keys from the Credential Report

IAM generates an account-wide CSV with every user, both key slots, when each key was created, and when and where it was last used:

# rotation/iam_keys.py
import boto3, csv, io, time, datetime as dt

def credential_report(session):
    iam = session.client("iam")
    while iam.generate_credential_report()["State"] != "COMPLETE":
        time.sleep(2)
    body = iam.get_credential_report()["Content"].decode()
    return list(csv.DictReader(io.StringIO(body)))

def stale_keys(rows, max_age_days=90):
    now = dt.datetime.now(dt.timezone.utc)
    for r in rows:
        for n in (1, 2):
            if r[f"access_key_{n}_active"] != "true":
                continue
            created = dt.datetime.fromisoformat(r[f"access_key_{n}_last_rotated"])
            used = r[f"access_key_{n}_last_used_date"]
            yield {
                "user": r["user"], "slot": n,
                "age_days": (now - created).days,
                "last_used": None if used in ("N/A", "no_information") else used,
                "last_service": r[f"access_key_{n}_last_used_service"],
                "last_region": r[f"access_key_{n}_last_used_region"],
                "stale": (now - created).days > max_age_days,
            }

Three things about this report catch people out. It is cached: IAM regenerates it at most once every four hours, so a key you deactivated ten minutes ago still shows as active. It does not contain the access key ID, so the agent joins each slot to list-access-keys by creation date to get the AKIA... it will need later. And last_rotated is simply the key's creation time. IAM has no concept of rotating a key in place, only of creating a new one.

The cheapest findings fall out here with no further work. A key that is 400 days old with last_used of N/A was never used at all. A key last used 200 days ago belongs to something that no longer runs. Neither needs rotating. They need deleting.

Step 2: Inventory Secrets Manager, Including Rotation That Is Enabled but Broken

list-secrets returns the rotation state for every secret in a region in one paginated call:

# rotation/secrets.py
def secrets(session, region):
    sm = session.client("secretsmanager", region_name=region)
    for page in sm.get_paginator("list_secrets").paginate():
        for s in page["SecretList"]:
            yield {
                "name": s["Name"], "arn": s["ARN"],
                "rotation_enabled": s.get("RotationEnabled", False),
                "rotation_days": s.get("RotationRules", {}).get("AutomaticallyAfterDays"),
                "last_rotated": s.get("LastRotatedDate"),
                "last_changed": s.get("LastChangedDate"),
                "last_accessed": s.get("LastAccessedDate"),
                "next_rotation": s.get("NextRotationDate"),
                "managed_by": s.get("OwningService"),
            }

That gives four distinct findings, and a scanner that only checks RotationEnabled sees one of them:

  1. Rotation off, value old. RotationEnabled is false and LastChangedDate is past your policy. The classic.
  2. Rotation on, not happening. RotationEnabled is true but LastRotatedDate is older than the interval plus a few days of slack. The rotation Lambda is failing and nobody is watching.
  3. Rotation stuck halfway. A previous attempt died between steps.
  4. Nobody reads it. LastAccessedDate is months old. It has day granularity only, which is plenty for this purpose.

Number three needs one more call. A rotation moves the AWSPENDING staging label onto a new version, tests it, then promotes it to AWSCURRENT. If the function fails midway, AWSPENDING stays attached to a version that is not current, and Secrets Manager keeps retrying that half-finished rotation instead of starting a clean one:

aws secretsmanager describe-secret --secret-id prod/orders/db \
  --query 'VersionIdsToStages'

If the output shows AWSPENDING on a different version ID than AWSCURRENT, the secret is stuck. The cause is in the rotation function's logs, and the failures themselves are in CloudTrail as RotationFailed events from secretsmanager.amazonaws.com. The agent attaches the last such event to the finding so the reviewer starts with the error and not with the symptom.

Secrets with OwningService set (an RDS managed master password, for example) are rotated by the owning service. The agent reports them as healthy and leaves them alone.

Step 3: Prove Who Still Uses Each Key

This is the step that turns a list of old keys into work someone will actually approve. CloudTrail records the access key ID on every call, and lookup-events can filter on it for the last 90 days:

aws cloudtrail lookup-events \
  --lookup-attributes AttributeKey=AccessKeyId,AttributeValue=AKIAIOSFODNN7EXAMPLE \
  --max-results 50 \
  --query 'Events[].[EventTime,EventSource,EventName]' --output table

That answers "is it used". To answer "by what", the agent groups by source in Athena against the trail's table:

SELECT sourceipaddress, useragent, eventsource,
       count(*) AS calls, max(eventtime) AS last_seen
FROM cloudtrail_logs
WHERE useridentity.accesskeyid = 'AKIAIOSFODNN7EXAMPLE'
  AND eventtime > date_format(date_add('day', -30, now()), '%Y-%m-%dT%H:%i:%sZ')
GROUP BY 1, 2, 3
ORDER BY calls DESC;

The sourceipaddress and useragent pair is the fingerprint of a consumer. One NAT gateway address with a Boto3/1.34 Python/3.11 agent is one service in one VPC. A GitHub-hosted runner range with aws-cli/2 is a CI workflow. Two unrelated fingerprints on the same key means the key was copied somewhere, and that changes the plan: every consumer has to move before the old key goes inactive.

One trap: a default trail records management events only. A key that does nothing except PutObject into a bucket produces no rows here, yet its last_used_service in the credential report says s3 and yesterday's date. When the two sources disagree, the agent believes the credential report, labels the consumer unknown (data events only), and refuses to propose deactivation until someone enables S3 data events for that bucket or names the owner. A key with a recent last-used date and no identified consumer is never safe to touch.

Step 4: Map the Kubernetes Consumers of Each Secret

For Secrets Manager secrets the consumers are usually pods, reached through External Secrets Operator. The mapping from secret to workload is all in the cluster:

kubectl get externalsecrets -A -o json | jq -r '
  .items[] | [.metadata.namespace, .spec.target.name // .metadata.name,
              .spec.refreshInterval,
              ([.spec.data[]?.remoteRef.key] | unique | join(","))] | @tsv'

Then, for each target Secret, the agent finds the workloads that reference it and records how they reference it, because that decides whether rotation is safe:

How the pod reads the SecretSees a new valueRotation-safe
Volume mountYes, after the kubelet sync periodYes, if the app re-reads the file
Volume mount with subPathNeverNo
env with secretKeyRef or envFromOnly on pod restartOnly with a restart trigger
env plus a Reloader annotationYes, by rolling restartYes

An environment variable is a copy taken at container start. If Secrets Manager rotates a database password on Tuesday and the Deployment has no restart trigger, the pods keep the old password until something else restarts them. With single-user rotation the old password is invalid the moment rotation finishes, so every new connection fails. With connection pooling the failure is delayed until connections recycle, so the outage shows up hours after the cause and nobody connects the two. If you have ever traced a wave of CrashLoopBackOff restarts back to an authentication error, this was probably it.

So the agent flags three mismatches before it will recommend enabling rotation: an ExternalSecret refreshInterval longer than a day on a secret that rotates, a consumer reading through env with no reloader.stakater.com/auto: "true" annotation or equivalent, and any subPath mount. For databases it also recommends the alternating-users rotation strategy over single-user, since alternating keeps the previous credential valid until the following rotation and gives slow consumers a full interval to catch up.

Step 5: The Model Picks a Verdict

Everything so far is deterministic collection. The model receives one record per credential (age, last use, consumer fingerprints, rotation state, consumer read mode) and makes the call that takes a human twenty minutes per key:

SYSTEM = (
    "You triage long-lived credentials. You receive computed facts only. "
    "Return one verdict per credential as JSON, with a one-paragraph reason "
    "citing the facts.\n"
    "delete_unused: no use in 90 days per BOTH the credential report and "
    "CloudTrail, or never used.\n"
    "eliminate: the consumer runs somewhere a role can be assumed (EKS pod, "
    "EC2, Lambda, GitHub Actions). Recommend IRSA or Pod Identity, an "
    "instance profile, or OIDC federation. Prefer this over rotate_key "
    "whenever it applies.\n"
    "rotate_key: the consumer is identified and cannot assume a role "
    "(on-prem host, third-party SaaS). List every consumer fingerprint.\n"
    "enable_rotation: Secrets Manager secret, rotation off, all consumers "
    "pick up new values without manual action.\n"
    "fix_consumer_first: rotation would break a consumer (env var with no "
    "restart trigger, subPath mount, refresh interval too long). Name the "
    "workload and the change.\n"
    "repair_rotation: rotation enabled but overdue or stuck in AWSPENDING.\n"
    "needs_human: a consumer is unknown, or fingerprints suggest the key was "
    "copied. Never propose deactivation with an unknown consumer.\n"
    "Do not infer a consumer from a user name. svc-foo is a label, not evidence."
)

A run against a mid-sized account looks like this:

CredentialAgeEvidenceVerdict
svc-legacy-etl key 11,140 dnever useddelete_unused
ci-deployer key 1610 dGitHub runner IPs, aws-cli/2eliminate (OIDC)
svc-report-uploader key 2402 dused yesterday, S3 only, no CloudTrail rowsneeds_human
partner-sftp-sync key 1233 done static IP, vendor user agentrotate_key
prod/orders/db380 drotation off, 3 Deployments via envFrom, no Reloaderfix_consumer_first
prod/billing/db71 drotation on, 30 d interval, AWSPENDING stuckrepair_rotation

The eliminate row is the one that matters most. A rotated key is still a long-lived key, and the next audit finds it again in 90 days. A CI job that assumes a role through OIDC has no stored credential to rotate, leak, or forget. The GitHub Actions security agent covers the workflow side of that change, and once the role exists, the IAM right-sizing agent can shrink it to what the job really calls.

Step 6: Ship Rotation Config as a PR, Deactivate Behind an Approval

Enabling rotation is a Terraform change, opened as a pull request alongside the consumer fix it depends on:

resource "aws_secretsmanager_secret_rotation" "orders_db" {
  secret_id           = aws_secretsmanager_secret.orders_db.id
  rotation_lambda_arn = aws_lambda_function.rds_rotation_alternating.arn

  rotation_rules {
    automatically_after_days = 30
  }
}

Be aware that applying this resource triggers an immediate first rotation unless you configure it otherwise. That is why fix_consumer_first exists as a separate verdict: the Reloader annotation or the switch to a volume mount merges and rolls out before this PR is even opened, and the PR description links the merged consumer change as its precondition.

For IAM keys, the sequence uses the second key slot so that old and new overlap:

# 1. CI job, not the agent: create the new key and write it straight to the store
aws iam create-access-key --user-name partner-sftp-sync \
  --query 'AccessKey.[AccessKeyId,SecretAccessKey]' --output text \
  | ./write-to-secrets-manager.sh prod/partner-sftp/aws

# 2. After the consumer redeploys: confirm traffic moved to the new key
aws iam get-access-key-last-used --access-key-id AKIANEWKEYEXAMPLE

# 3. Approved action: deactivate the old key (reversible)
aws iam update-access-key --user-name partner-sftp-sync \
  --access-key-id AKIAIOSFODNN7EXAMPLE --status Inactive

The agent proposes step 3 only when the new key's last-used timestamp is recent and the old key's has stopped advancing for at least 48 hours. Deletion happens 14 days after deactivation, in a separate approved step, because Inactive can be flipped back in seconds and a deleted key cannot be recovered at all. If the user already has two active keys, there is no free slot, and the finding goes to a human to decide which one dies first.

Guardrails That Live in Code

  • The model never sees a secret value. The agent's role has no secretsmanager:GetSecretValue and no iam:CreateAccessKey. Key creation runs in a pipeline step whose output is piped to the store and masked from logs, following the same rule as the rest of the secrets management setup for agents: metadata in, never material.
  • One write, and it is reversible. The only mutating permission is iam:UpdateAccessKey, and the wrapper rejects any call whose status is not Inactive. There is no iam:DeleteAccessKey on the agent role at all.
  • Unknown consumer means no action. The wrapper drops any deactivation proposal for a key whose record contains an unidentified fingerprint, whatever the verdict says.
  • Evidence is re-checked at execution time. Approval may come two days after the proposal. Immediately before deactivating, the wrapper calls get-access-key-last-used again and aborts if the date moved.
  • A human approves, and the approval is recorded. Deactivation goes through the same approval gate as every other write on this site, with the consumer evidence in the request.
  • Blast radius is capped. At most five deactivations per run and never two keys belonging to the same user, so a bad inference costs one rollback and not an afternoon.

Honest Limits

Last-used data proves use. It cannot prove absence of need. A key used once a year by an annual reporting job looks identical to a dead key for 364 days. The 90-day window is a policy choice, and the deactivate-then-wait step exists precisely because the window will sometimes be wrong.

Fingerprints identify a network location and a client library, not a team. A NAT gateway address narrows the consumer to a VPC that may hold forty services. The agent says "something in vpc-prod-a using the Java SDK", and a person still has to walk that last stretch.

A request signed with an inactive key is rejected at authentication, and you should not count on finding that failure in CloudTrail. The signal that you deactivated too early comes from the consumer's own error logs or from its owner. Tell owners before you deactivate, not after.

Rotation is the weaker fix. The agent can rotate a key for years and each cycle carries the same small risk of breaking a consumer. Every key it converts to a role is a key it never has to reason about again. Measure the agent by how many long-lived credentials are left, not by how fresh they are.

#ai#security#aws#devops#automation#kubernetes#terraform
D
DevToCashAuthor

Senior DevOps/SRE Engineer · 10+ years · Professional Trader (IDX, Crypto, US Equities)

I write about real infrastructure patterns and trading strategies I use in production and in live markets. No courses, no affiliate hype — just documentation of what actually works.

More about me →