Sub topic 13
Generating least-privilege policies from CloudTrail
This chapter assumes you can read IAM policy JSON, run AWS CLI commands, and know what a CloudTrail trail is. It also assumes you have read the earlier chapters on unused access findings and policy recommendations.
Why generate a policy from activity
Unused access findings and policy recommendations work on permissions that already exist. They tell you what to remove. Policy generation works the other way. You point Access Analyzer at an IAM user or role, it reads the CloudTrail events that principal produced, and it writes a new identity-based policy that allows only what the principal actually did.
Policy generation fits two situations:
- A role was created with broad permissions, such as
AdministratorAccessor aAction: "*"policy. It has now run a real workload for weeks, and you want to replace the broad policy. - A team built something in a development account with generous permissions and now needs a production policy based on what the application really calls.
Policy generation is a starting point, not a finished policy. You must review it before you attach it.
How generation works
Access Analyzer does not watch the principal live. It reads logs that already exist. The process has four parts:
- You choose a principal (user or role), a CloudTrail trail, a time window of up to 90 days, and a service role that Access Analyzer can assume.
- Access Analyzer assumes that service role and reads the trail's events from the S3 bucket where the trail stores logs.
- It extracts the actions the principal called and, where CloudTrail records them, the resources.
- It returns a policy. For services that provide action-level last-accessed data, it uses that data to fill in actions that CloudTrail alone does not show.
Prerequisites in your account
Generation fails or returns an incomplete policy if these are missing.
- A trail that covers the period. The trail must have been logging for the whole time window. Events from before the trail existed cannot appear.
- Data events, if you need them. Management events cover most control-plane actions, such as
iam:PassRoleorec2:RunInstances. Object-level S3 actions likes3:GetObjectand LambdaInvokeare data events. If the trail does not log data events, those actions are missing from the draft. - A service role. Access Analyzer needs permission to read your trail and log bucket. You can let the console create this role, or create it yourself.
A service role trusts the Access Analyzer service principal:
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Principal": { "Service": "access-analyzer.amazonaws.com" },
"Action": "sts:AssumeRole"
}
]
}Its permissions policy needs to let it read the trail and logs, and look up service last-accessed data. Scope the S3 resources to your log bucket:
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"cloudtrail:GetTrail",
"cloudtrail:DescribeTrails",
"cloudtrail:ListTrails",
"cloudtrail:LookupEvents",
"iam:GenerateServiceLastAccessedDetails",
"iam:GetServiceLastAccessedDetails"
],
"Resource": "*"
},
{
"Effect": "Allow",
"Action": ["s3:GetObject", "s3:ListBucket"],
"Resource": [
"arn:aws:s3:::example-cloudtrail-logs",
"arn:aws:s3:::example-cloudtrail-logs/*"
]
}
]
}If the log bucket is encrypted with a customer managed KMS key, the service role also needs kms:Decrypt on that key. A missing KMS permission is a common reason a generation job fails.
Running a generation job from the CLI
The job is asynchronous. You start it, receive a job ID, and poll until it finishes.
aws accessanalyzer start-policy-generation \
--policy-generation-details '{"principalArn":"arn:aws:iam::111122223333:role/orders-app"}' \
--cloud-trail-details '{
"accessRole": "arn:aws:iam::111122223333:role/AccessAnalyzerMonitorServiceRole",
"startTime": "2026-09-01T00:00:00Z",
"endTime": "2026-11-25T00:00:00Z",
"trails": [
{
"cloudTrailArn": "arn:aws:cloudtrail:us-east-1:111122223333:trail/org-trail",
"allRegions": true
}
]
}'The response contains a jobId. Check its progress and fetch the result:
aws accessanalyzer list-policy-generations \
--principal-arn arn:aws:iam::111122223333:role/orders-app
aws accessanalyzer get-generated-policy \
--job-id JOB_ID \
--include-resource-placeholders \
--include-service-level-templateThe job status is IN_PROGRESS, SUCCEEDED, FAILED, or CANCELED. Use cancel-policy-generation to stop a job you started by mistake. Generated results are kept only for a limited time, so copy a policy you want to keep into your own repository soon after it succeeds.
The two flags on get-generated-policy change what you get back:
| Flag | What it adds |
|---|---|
| `--include-resource-placeholders` | Uses placeholders such as `${BucketName}` where CloudTrail did not give a usable resource ARN, so you know exactly what to fill in |
| `--include-service-level-template` | Returns a template that lists the services used and lets you pick actions yourself, for services where action-level data is not available |
Reading the generated output
A draft often looks like this:
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": ["s3:GetObject", "s3:PutObject"],
"Resource": "arn:aws:s3:::${BucketName}/orders/*"
},
{
"Effect": "Allow",
"Action": ["sqs:ReceiveMessage", "sqs:DeleteMessage"],
"Resource": "arn:aws:sqs:us-east-1:111122223333:orders-queue"
}
]
}Go through it with these checks:
- Replace every placeholder. The policy is not valid until
${BucketName}and similar values are real ARNs. - Check the resource scope. If a statement uses
"Resource": "*", ask whether a narrower ARN is possible. - Add conditions yourself. Generation does not write conditions such as
aws:SourceVpcoraws:PrincipalOrgID. If the original policy had conditions that mattered, put them back. - Look for gaps. Compare the draft with what the application is supposed to do.
Gotchas and failure modes
Generated policies describe the past. They are only as complete as the activity in the window.
- Rare operations are missing. A quarterly report job, a disaster recovery failover, or a yearly certificate rotation may not have run in the window. Their actions will not appear, and the application will break the first time they run. A 90-day window helps, but it does not remove this risk.
- Not every call is logged. Some actions are not recorded by CloudTrail, and data events are only present if you turned them on. Missing data events produce a policy that is too narrow.
- Role chaining and
iam:PassRole. Passing a role to a service needsiam:PassRoleon that role. Check that it is in the draft, and scoped to the specific role ARN. - Permission to the trail is not permission to the workload. Reading the logs requires the service role. It does not mean the generated policy includes any of the service role's permissions.
- Activity by other principals is excluded. The draft covers only the principal you chose. Another role that assumes this one is tracked by session, not as a separate source.
A safe rollout pattern
Combine this chapter with the earlier ones:
- Generate a draft for the role.
- Fill in placeholders and tighten resources.
- Run
validate-policyon the draft to catch grammar and best-practice problems. - Run
check-no-new-accesswith the generated policy as the new policy and the current policy as the existing one. It should report that the new policy grants no access the old one did not, which confirms you only narrowed permissions. - Attach the new policy, keep the old one in place for a short overlap, then detach the old one.
- Watch the unused access analyzer afterward. New findings against the role show whether the draft still contains permissions nobody uses.
aws accessanalyzer validate-policy \
--policy-type IDENTITY_POLICY \
--policy-document file://generated-policy.json
aws accessanalyzer check-no-new-access \
--policy-type IDENTITY_POLICY \
--existing-policy-document file://policy-current.json \
--new-policy-document file://generated-policy.jsonChoosing between generation and recommendations
| Situation | Better tool |
|---|---|
| An existing role has an unused access finding for specific permissions | Policy recommendation, which names permissions to remove |
| A role has a very broad policy and you want to build a new one from scratch | Policy generation |
| A new application needs a policy before it runs in production | Policy generation from a test environment's CloudTrail |
| You want continuous detection, not a one-time rewrite | Unused access analyzer |
Recommendations subtract from a policy you already have. Generation builds a new one from observed behavior. Many teams use generation once to get a first tight policy, then rely on the unused access analyzer to keep it tight.
Exercise
A role ran an order-processing workload for 60 days. You generate a policy with a 60-day window and it contains no s3:PutObject action, although the application uploads receipts to S3. Give two likely causes and one step to fix each.
Show answer
Cause 1: the trail did not log S3 data events, so object-level actions like s3:PutObject were never recorded. Fix: enable data events for the bucket on the trail, let the workload run, and generate again. Cause 2: the upload happens only in a rare path, such as month-end, that did not run in the 60-day window. Fix: widen the window up to 90 days if the trail covers it, or add the action by hand after confirming with the application owners, then validate the result.
Exercise
Why should you run check-no-new-access on a generated policy before replacing the existing one?
Show answer
The check compares the proposed policy with the current one and reports whether the proposed policy grants any access the current one does not. If the generated policy only narrows permissions, the check passes. If a placeholder replacement or a manual edit accidentally adds access, the check shows it before the policy reaches production.