Use CloudTrail to find the calls your AI coding agent made, spot the risky ones and turn what it really used into a smaller IAM role.

In February 2026 Alexey Grigorev of DataTalks.Club shared a hard story. An AI coding agent ran terraform destroy and took out a production database along with its snapshots. He wrote it up openly in this interview with Rootly. I respect him for that. Most of us have handed an agent our credentials and hoped for the best. I know I have.

Elastic now ships a detection rule for destructive AWS CLI commands run by a GenAI agent. That tells you this is not a rare case anymore.

So here is the question I kept asking myself. If an agent did something in my account last night, could I tell? Most of the time the answer was no. The agent runs with my SSO admin role. In CloudTrail its calls look exactly like mine.

This is how I dig them out by hand.

The CloudTrail fields that matter

Every account has CloudTrail event history. It holds 90 days of management events per region and costs nothing. These fields do most of the work:

  • userAgent: the AWS CLI and SDKs put their name and version here. Some agent tools and MCP servers add their own marker. Many do not. Treat it as a hint, never as proof.
  • userIdentity.arn: for an assumed role this ends with the role session name. If agents start sessions with a name like agent-ritom you can filter on it.
  • userIdentity.accessKeyId: keys starting with ASIA are temporary and belong to one session. Keys starting with AKIA are static user keys. An agent on an AKIA key is a finding on its own.
  • sourceIPAddress: your laptop, a CI runner or a cloud sandbox. Handy when the agent runs somewhere you do not.
  • readOnly and errorCode: writes are what you care about first. AccessDenied tells you what the agent tried and could not do. That is often the most useful part.

One gotcha up front. IAM and other global services log to us-east-1. Always check that region too.

Pull the calls with the CLI and jq

Start with the write calls for one person in one region:

aws cloudtrail lookup-events --region us-east-1 \ --lookup-attributes AttributeKey=Username,AttributeValue=jane@example.com \ --start-time 2026-11-20T00:00:00Z \ --query 'Events[].CloudTrailEvent' --output json \ | jq -r '.[] | fromjson | select(.readOnly==false) | [.eventTime, .eventSource, .eventName, .userIdentity.accessKeyId, .sourceIPAddress, .userAgent, (.errorCode // "-")] | @tsv' 

Then group by access key. With temporary credentials each key is one session, so this gives you a rough list of sessions with their user agents:

aws cloudtrail lookup-events --region us-east-1 \ --start-time 2026-11-20T00:00:00Z \ --query 'Events[].CloudTrailEvent' --output json \ | jq -r '[.[] | fromjson] | group_by(.userIdentity.accessKeyId)[] | {key: .[0].userIdentity.accessKeyId, who: .[0].userIdentity.arn, agents: ([.[].userAgent] | unique), calls: length, writes: ([.[] | select(.readOnly==false)] | length)}' 

lookup-events takes one lookup attribute per call and is rate limited. It is fine for one person and one day. It gets slow for a busy account.

Query a trail with Athena

If you have a trail writing to S3 you can create an Athena table from the CloudTrail console. Then you can search everything at once:

SELECT eventtime, eventsource, eventname, useridentity.arn AS principal, useridentity.accesskeyid AS key, sourceipaddress, useragent, errorcode FROM cloudtrail_logs WHERE readonly = 'false' AND eventtime > '2026-11-20T00:00:00Z' AND (regexp_like(lower(useragent), 'claude|cursor|copilot|codex|gemini|kiro|mcp|langchain') OR regexp_like(lower(useridentity.arn), '/(agent|claude|mcp)[^/]*$')) ORDER BY eventtime; 

CloudTrail Lake has the same fields with camel case names. The same idea works there.

Which calls should scare you

Not every write is a problem. These are the ones I alert on:

  • anything on iam.amazonaws.com that is not a read
  • Delete* and Terminate* calls, like DeleteDBInstance, DeleteDBSnapshot or TerminateInstances
  • AuthorizeSecurityGroupIngress with 0.0.0.0/0 or ::/0
  • DisableKey, ScheduleKeyDeletion and PutKeyPolicy on KMS
  • changes to S3 Block Public Access
  • StopLogging, DeleteTrail and UpdateTrail on CloudTrail
  • any Organizations write

Five or more AccessDenied errors in one session also deserve a look. That usually means the agent was trying different routes to get something done.

Build a smaller role from what the agent really used

Once you know what the agent calls, give it its own role. IAM Access Analyzer can write the first draft of the policy from CloudTrail. It needs a trail and a service role that can read the trail bucket:

aws accessanalyzer start-policy-generation \ --policy-generation-details principalArn=arn:aws:iam::111122223333:role/agent-dev \ --cloud-trail-details '{ "trails": [{"cloudTrailArn": "arn:aws:cloudtrail:us-east-1:111122223333:trail/main", "allRegions": true}], "accessRole": "arn:aws:iam::111122223333:role/AccessAnalyzerTrailRead", "startTime": "2026-10-23T00:00:00Z" }' aws accessanalyzer get-generated-policy --job-id <job id from above> 

Review what comes back. I keep only the reads for the agent role. If the agent truly needs to write, I do that step myself or give it a separate role that I assume on purpose.

Guardrails that stop the next one

A role for reading only. Set MaxSessionDuration to 3600 so sessions end after an hour. Start sessions with a clear name:

aws sts assume-role --role-arn arn:aws:iam::111122223333:role/agent-dev \ --role-session-name agent-jane --source-identity jane 

A label in the user agent. Set AWS_SDK_UA_APP_ID=my-agent in the shell the agent uses. The AWS CLI v2 and the SDKs add it to the user agent so the calls stand out in CloudTrail.

A permissions boundary. Attach one to every agent role. Then even if the agent finds an IAM write it can use, it cannot give itself more than the boundary allows.

An SCP for the worst calls. In AWS Organizations you can deny destructive calls for every role whose name starts with agent-:

{ "Version": "2012-10-17", "Statement": [{ "Sid": "NoDestructiveCallsFromAgents", "Effect": "Deny", "Action": [ "rds:DeleteDBInstance", "rds:DeleteDBCluster", "rds:DeleteDBSnapshot", "rds:DeleteDBClusterSnapshot", "ec2:TerminateInstances", "s3:DeleteBucket", "cloudtrail:StopLogging", "cloudtrail:DeleteTrail", "kms:ScheduleKeyDeletion", "iam:*" ], "Resource": "*", "Condition": {"ArnLike": {"aws:PrincipalArn": "arn:aws:iam::*:role/agent-*"}} }] } 

Also turn on deletion protection for production databases and keep backups somewhere the agent role cannot touch. None of this helps if the agent still runs as your admin role. That is the first thing to change.

A few more gotchas

  • Event history covers management events only. S3 object reads need data events on a trail.
  • Events land a few minutes after the call.
  • A user agent can be set to anything. Session names and roles are much more reliable.

Disclosure: I built a tool for this

I got tired of running these queries by hand, so I built AI Agent Activity Audit. You connect an account with a CloudFormation role that can only read CloudTrail event history and IAM role details. Every 10 minutes it picks out agent calls by user agent, session name, roles you mark as agent roles or your own patterns. It shows why each one matched. It groups them into sessions, alerts on Slack or email for the risky calls above, flags agents on admin roles or static keys and drafts a role for reading only from what the agent actually called. It needs no trail. There is a 14 day free trial. I am the person who built it, so weigh my opinion with that in mind. Everything above works fine without it.