Playbook: IAM role too broad
Right-size an over-permissive IAM role safely using last-accessed data, CloudTrail and IAM Access Analyzer policy generation, with a staged rollout and rollback so you reduce risk without breaking a year-end job.
Assumes: .NET 10 LTS · AWS CLI v2 · IAM Access Analyzer · IAM last accessed information · Region us-east-1. Verified against official sources on 2026-11-18.
Learning objectives
By the end of this playbook you can:
- Explain why "just tighten the role" is risky and what a safe right-sizing sequence looks like.
- Use IAM last accessed information to find services and actions a role has not used.
- Use IAM Access Analyzer policy generation to draft a least-privilege policy from CloudTrail activity, and know what it cannot see.
- Plan a staged change with testing, monitoring for
AccessDeniedand a ready rollback. - Handle the banking trap: rare but critical activity such as quarter-end and year-end jobs that the observation window missed.
- Run a C# tool that compares a role's policy with its last-accessed data and lists removal candidates.
Prerequisites
- Least privilege and IAM Access Analyzer
- IAM in depth and Policy evaluation logic
- CloudTrail for banks
- AccessDenied and IAM policy evaluation, the sibling playbook for reading denials
- Tools: AWS CLI v2 with the
learn-sandboxprofile; .NET 10 SDK for the tool
Why this matters in banking
A role named hl-reporting-role was created two years ago for a reporting job. Under deadline pressure the team gave it s3:*, dynamodb:*, sqs:*, sns:* and kms:* on Resource: "*". An internal audit now finds it, and a penetration tester shows that a vulnerability in the reporting container would let an attacker read every bucket and decrypt with any key the role can reach. The finding is "role too broad, privilege escalation potential", and the audit wants it fixed in two weeks.
The danger of the fix is symmetric to the danger of the flaw. If you remove permissions the role really needs, the quarter-end regulatory report fails on the night it must run. A calm, evidence-based method gets you both: smaller blast radius and no surprise outage.
The idea in plain language
A role is too broad when it can do more than the work it actually does. Right-sizing means comparing what it is allowed to do with what it has done, trimming the difference, and proving the trimmed version still does the work.
Three evidence sources, with different strengths:
| Source | Answers | Weakness |
|---|---|---|
| Last accessed information (IAM) | Which services (and for some, which actions) the role used, and when | Retention is limited (⚠ VERIFY the current window, commonly up to 400 days), and action-level data exists only for some services |
| CloudTrail activity | Exactly which API calls the role made, with resources | Data events (object-level S3, DynamoDB item-level) are opt-in; only what was logged is seen |
| IAM Access Analyzer policy generation | A draft policy built from CloudTrail activity over a chosen period | Needs CloudTrail with the right events, up to a maximum look-back (⚠ VERIFY, currently 90 days), may use wildcards where logs lack detail, and never knows about calls that did not happen in the window |
Analogy: The role is a bank staff keycard that opens every door in the building. To fit a smaller card you review the door log for the last quarter. But the vault only opens at year-end, so a quarter's log will never show it. If you cut the vault from the card because the log is silent, the year-end audit fails. Right-sizing needs the log and a conversation with the people who use the card.
What problem the AWS services solve
- Last accessed data removes guesswork about unused services. It is the fastest first cut.
- Policy generation turns observed API calls into a draft policy you can review, replacing hand-writing from scratch.
- Access Analyzer unused-access findings (a paid feature, ⚠ VERIFY pricing) continuously flag unused roles, unused permissions and unused access keys, so over-breadth is found by the platform before an auditor finds it.
- IAM Policy Simulator and
simulate-principal-policytest a candidate policy against a list of actions before you attach it. - Permission boundaries and SCPs put an outer ceiling over what a role can ever do, which reduces damage while you work on the inner policy.
Limits worth knowing: policy generation reports actions it saw, and for some services only resource ARNs partially. It cannot generate conditions that express your intent (for example "only keys tagged Project=hl-reporting"). A human adds those.
Microsoft / Azure comparison
| You know (Microsoft/Azure) | AWS equivalent | What's different |
|---|---|---|
| Entra ID permissions management / Access Reviews | IAM Access Analyzer unused access, last accessed data | AWS gives per-role evidence, but the review process is yours to run |
| Azure RBAC role "Contributor" on a subscription | A role with *:* or service:* on * | The AWS equivalent of "Owner" is AdministratorAccess; anything with iam:* is effectively near-admin |
| Azure Activity Log for role usage | CloudTrail, plus IAM last accessed | Last accessed is a built-in summary, CloudTrail is the detail |
| Privileged Identity Management (just-in-time) | IAM Identity Center permission sets with session duration, or break-glass roles | Time-bound elevation is a design you build, not a single switch |
| Azure Policy deny assignments | SCPs and permission boundaries | Ceilings, not grants; they never give permissions |
Architecture
The right-sizing loop
Blast-radius ceiling while you work
Step-by-step implementation
Minutes 0 to 10: inventory, owner and ceiling
- List everything that grants the role permissions: managed policies, inline policies, the permissions boundary if any, and any SCPs in the path.
- Read the trust policy: who can assume it (a service, another role, a person)? A broad trust policy is its own finding.
- Identify the owner and the jobs that use the role. Ask: "what runs rarely?" Write down quarter-end, year-end, disaster recovery tests, annual regulatory submissions and incident break-glass uses.
- Immediate risk reduction without touching the policy: if possible, add a permissions boundary or an SCP that denies the most dangerous actions (IAM changes, disabling logging, KMS key deletion).
Minutes 10 to 25: collect last-accessed evidence
Generate service last accessed data for the role at action level where supported, wait for the job to complete and download it. Unused services are your first removal candidates. A service with a recent access date needs a closer look at which actions.
Minutes 25 to 45: generate and review a draft policy
Run Access Analyzer policy generation over the longest period your CloudTrail covers (up to its maximum). Review the draft line by line:
- Replace wildcard resources with specific ARNs where you can.
- Add conditions (tag, VPC endpoint, KMS encryption context) that express the intent.
- Combine with last-accessed evidence: anything in the draft that last-accessed says was unused is suspicious.
- Add known rare actions from the owner interview even though the logs did not show them. Record why each one is there.
Minutes 45 to 60: test
Run the candidate policy through simulate-principal-policy for a list of must-allow and must-deny actions, then deploy it to a non-production copy of the workload and run the job. A must-deny list matters: include a few things the old role could do that the new one must not (for example s3:DeleteBucket).
Minutes 60 to 80: stage, monitor, remove
- Attach the new narrow policy alongside the old broad one. Nothing breaks, because permissions are additive.
- Before detaching anything, add a monitoring query or alarm for
AccessDeniedevents from this role. Then detach the old broad policy in a planned change window and watch the alarm. - Keep the old policy document saved so rollback is one command.
- Monitor through at least one full business cycle, including month-end, and ideally the longest cycle the role supports. Where year-end is far away, test the rare job in non-production with realistic data.
- After the clean period, remove the old policy permanently and record the change.
AWS Console instructions
- Console → IAM → Roles → (role) → Access Advisor tab: shows services the role can access and when it last did. Choose Last accessed columns and expand a service for tracked actions where available.
- Console → IAM → Roles → (role) → Permissions tab: the Generate policy button (in the section "Generate policy based on CloudTrail events") starts Access Analyzer policy generation. Pick the period, the trail and the service access role.
- Console → IAM → Access Analyzer → Unused access (if you created the analyzer): lists findings for unused permissions per role.
- Console → IAM → Policies → Create policy → JSON to review the draft, with the Policy validation panel showing warnings.
- Console → CloudTrail → Event history: filter User name or Resource name for the role and look for
errorCode = AccessDeniedafter the change.
AWS CLI
# 1. Start a service last accessed job for the role at action level.
JOB=$(aws iam generate-service-last-accessed-details \
--arn arn:aws:iam::111122223333:role/hl-reporting-role \
--granularity ACTION_LEVEL \
--query JobId --output text --profile learn-sandbox)
# 2. Fetch the result (repeat until JobStatus is COMPLETED), saved for the analysis tool.
aws iam get-service-last-accessed-details --job-id "$JOB" --profile learn-sandbox > lastaccessed.json
# 3. Which actions of a particular service were used, and by which entity (replace the namespace).
aws iam get-service-last-accessed-details-with-entities --job-id "$JOB" \
--service-namespace s3 --profile learn-sandbox
# 4. What does the role allow today? (Inventory.)
aws iam list-attached-role-policies --role-name hl-reporting-role --profile learn-sandbox
aws iam list-role-policies --role-name hl-reporting-role --profile learn-sandbox
# 5. Start Access Analyzer policy generation from CloudTrail activity (dates and ARNs are fictional).
aws accessanalyzer start-policy-generation \
--policy-generation-details '{"principalArn":"arn:aws:iam::111122223333:role/hl-reporting-role"}' \
--cloud-trail-details '{"accessRole":"arn:aws:iam::111122223333:role/hl-policy-generation-service","startTime":"2026-08-20T00:00:00Z","endTime":"2026-11-18T00:00:00Z","trails":[{"cloudTrailArn":"arn:aws:cloudtrail:us-east-1:111122223333:trail/hl-org-trail","allRegions":true}]}' \
--profile learn-sandbox
# 6. Retrieve the generated policy (use the JobId returned by the previous command).
aws accessanalyzer get-generated-policy --job-id <policy-generation-job-id> --profile learn-sandbox
# 7. Test the candidate policy for must-allow and must-deny actions.
aws iam simulate-custom-policy --policy-input-list file://candidate-policy.json \
--action-names s3:GetObject dynamodb:Query s3:DeleteBucket kms:ScheduleKeyDeletion \
--resource-arns "*" --profile learn-sandbox
# 8. After the change: look for denials from the role (Logs Insights over a CloudTrail log group, or Athena).
aws logs start-query --log-group-name /hl/cloudtrail \
--start-time $(date -d '7 days ago' +%s) --end-time $(date +%s) \
--query-string 'fields @timestamp, eventSource, eventName, errorCode
| filter userIdentity.sessionContext.sessionIssuer.arn like /hl-reporting-role/ and errorCode like /AccessDenied/
| stats count(*) by eventSource, eventName' \
--profile learn-sandboxInfrastructure as Code
The "after" state in code: a narrow role, an unused-access analyzer so the next over-broad role is found early. Roles in code also make rollback a Git revert.
using Amazon.CDK;
using Amazon.CDK.AWS.IAM;
using Constructs;
public class ReportingRoleStack : Stack
{
public ReportingRoleStack(Construct scope, string id, IStackProps props) : base(scope, id, props)
{
var role = new Role(this, "ReportingRole", new RoleProps
{
RoleName = "hl-reporting-role",
AssumedBy = new ServicePrincipal("ecs-tasks.amazonaws.com"),
Description = "Reporting job. Right-sized from last-accessed and CloudTrail evidence, see change record.",
MaxSessionDuration = Duration.Hours(1)
});
// Read only the report inputs, from one bucket prefix.
role.AddToPolicy(new PolicyStatement(new PolicyStatementProps
{
Sid = "ReadReportInputs",
Actions = new[] { "s3:GetObject" },
Resources = new[] { "arn:aws:s3:::hl-reporting-inputs/daily/*" }
}));
// Write report outputs to one prefix.
role.AddToPolicy(new PolicyStatement(new PolicyStatementProps
{
Sid = "WriteReportOutputs",
Actions = new[] { "s3:PutObject" },
Resources = new[] { "arn:aws:s3:::hl-reporting-outputs/reports/*" }
}));
// Query one table and its index only.
role.AddToPolicy(new PolicyStatement(new PolicyStatementProps
{
Sid = "QueryPaymentsTable",
Actions = new[] { "dynamodb:Query", "dynamodb:GetItem" },
Resources = new[]
{
"arn:aws:dynamodb:us-east-1:111122223333:table/hl-payments",
"arn:aws:dynamodb:us-east-1:111122223333:table/hl-payments/index/*"
}
}));
// KMS: decrypt/encrypt only with one key, only through S3 and DynamoDB.
role.AddToPolicy(new PolicyStatement(new PolicyStatementProps
{
Sid = "UseReportingKey",
Actions = new[] { "kms:Decrypt", "kms:GenerateDataKey" },
Resources = new[] { "arn:aws:kms:us-east-1:111122223333:key/11111111-2222-3333-4444-555555555555" },
Conditions = new Dictionary<string, object>
{
["StringEquals"] = new Dictionary<string, string> { ["kms:ViaService"] = "s3.us-east-1.amazonaws.com" }
}
}));
Amazon.CDK.Tags.Of(this).Add("Project", "cea-lab");
Amazon.CDK.Tags.Of(this).Add("Lab", "m17-playbook-iam-broad");
}
}The role resource itself (aws_iam_role.reporting) and its trust policy are omitted for brevity; keep the trust policy specific to the one service that must assume it.
Complete code
A tool that lists removal candidates
This tool reads two files you can produce with the CLI: the role's policy document (JSON) and the output of get-service-last-accessed-details (JSON). It works offline, so it needs no AWS credentials and is easy to test. It lists services the policy grants, whether they were used within a window and flags wildcard access.
using System.Text.Json;
if (args.Length < 2)
{
Console.WriteLine("usage: RoleRightSizer <policy.json> <lastaccessed.json> [windowDays=90] [asOf=yyyy-MM-dd]");
return 1;
}
var windowDays = args.Length > 2 ? int.Parse(args[2]) : 90;
var asOf = args.Length > 3 ? DateTimeOffset.Parse(args[3] + "T00:00:00Z") : DateTimeOffset.UtcNow;
var granted = ReadGrantedServices(File.ReadAllText(args[0]));
var lastAccessed = ReadLastAccessed(File.ReadAllText(args[1]));
Console.WriteLine($"As of {asOf:yyyy-MM-dd}, window {windowDays} days");
if (granted.Contains("*"))
Console.WriteLine("WARNING: the policy allows every service ('*'). Treat the whole policy as a finding.");
var keep = new List<string>();
var candidates = new List<string>();
foreach (var service in granted.Where(s => s != "*").OrderBy(s => s))
{
if (lastAccessed.TryGetValue(service, out var last) && last is not null)
{
var age = (asOf - last.Value).TotalDays;
if (age <= windowDays) keep.Add($"{service,-10} last used {last:yyyy-MM-dd} ({age:F0} days ago)");
else candidates.Add($"{service,-10} last used {last:yyyy-MM-dd} ({age:F0} days ago): STALE, ask the owner about rare jobs");
}
else
{
candidates.Add($"{service,-10} never accessed in the tracking period: remove candidate");
}
}
Console.WriteLine("\nUsed recently (narrow the actions and resources, do not remove):");
keep.ForEach(k => Console.WriteLine(" " + k));
Console.WriteLine("\nRemoval candidates (confirm with the owner before removing):");
candidates.ForEach(c => Console.WriteLine(" " + c));
Console.WriteLine("\nReminder: last-accessed data cannot see jobs that run less often than its tracking period.");
return candidates.Count > 0 || granted.Contains("*") ? 2 : 0;
// Returns the service prefixes (s3, dynamodb, ...) that Allow statements grant, or "*" for everything.
static HashSet<string> ReadGrantedServices(string policyJson)
{
var result = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
using var doc = JsonDocument.Parse(policyJson);
var statements = doc.RootElement.GetProperty("Statement");
var list = statements.ValueKind == JsonValueKind.Array ? statements.EnumerateArray().ToList() : new List<JsonElement> { statements };
foreach (var s in list)
{
if (!s.TryGetProperty("Effect", out var effect) || effect.GetString() != "Allow") continue;
if (!s.TryGetProperty("Action", out var action)) continue;
var actions = action.ValueKind == JsonValueKind.Array
? action.EnumerateArray().Select(a => a.GetString() ?? "")
: new[] { action.GetString() ?? "" };
foreach (var a in actions)
result.Add(a == "*" ? "*" : a.Split(':')[0]);
}
return result;
}
// Reads the CLI output of get-service-last-accessed-details into namespace -> last access time.
static Dictionary<string, DateTimeOffset?> ReadLastAccessed(string json)
{
var result = new Dictionary<string, DateTimeOffset?>(StringComparer.OrdinalIgnoreCase);
using var doc = JsonDocument.Parse(json);
if (!doc.RootElement.TryGetProperty("ServicesLastAccessed", out var services)) return result;
foreach (var s in services.EnumerateArray())
{
var ns = s.GetProperty("ServiceNamespace").GetString() ?? "";
DateTimeOffset? last = s.TryGetProperty("LastAuthenticated", out var la) && la.ValueKind == JsonValueKind.String
? DateTimeOffset.Parse(la.GetString()!)
: null;
result[ns] = last;
}
return result;
}Sample inputs (fictional) to run it against:
{
"Version": "2012-10-17",
"Statement": [
{ "Effect": "Allow", "Action": ["s3:*", "dynamodb:*", "sqs:*", "sns:*", "kms:*"], "Resource": "*" }
]
}{
"JobStatus": "COMPLETED",
"ServicesLastAccessed": [
{ "ServiceName": "Amazon S3", "ServiceNamespace": "s3", "LastAuthenticated": "2026-11-17T08:00:00+00:00", "TotalAuthenticatedEntities": 1 },
{ "ServiceName": "Amazon DynamoDB", "ServiceNamespace": "dynamodb", "LastAuthenticated": "2026-11-16T22:30:00+00:00", "TotalAuthenticatedEntities": 1 },
{ "ServiceName": "AWS Key Management Service", "ServiceNamespace": "kms", "LastAuthenticated": "2026-11-17T08:00:00+00:00", "TotalAuthenticatedEntities": 1 },
{ "ServiceName": "Amazon SNS", "ServiceNamespace": "sns", "LastAuthenticated": "2026-03-01T10:00:00+00:00", "TotalAuthenticatedEntities": 1 },
{ "ServiceName": "Amazon SQS", "ServiceNamespace": "sqs", "TotalAuthenticatedEntities": 0 }
]
}Run dotnet run -- policy.json lastaccessed.json 90 2026-11-18. Expected: S3, DynamoDB and KMS "used recently", SNS "STALE" and SQS "never accessed".
Code explained line by line
ReadGrantedServicesparses the policy withSystem.Text.Json'sJsonDocument, which reads JSON without needing a class model. IAM allowsStatementto be one object or an array, so the code handles both shapes.- Only
Effect: Allowstatements count as grants. ADenystatement would not widen the role. a.Split(':')[0]takes the service prefix from an action such ass3:GetObject. A bare*becomes a special marker, treated as a finding on its own.ReadLastAccessedmaps each service namespace to the last time the role used it. A service with noLastAuthenticatedfield was never used in the tracking period, so the value isnull.- The age calculation uses the
asOfdate that you pass in, so the same input always gives the same output: handy for tests and for reproducing a past review. - A stale service (used, but outside the window) is not simply removed: the tool says "ask the owner about rare jobs", which is the year-end trap in code.
- The exit code is 2 when there is anything to review, so a CI job can fail a pull request that adds a broad role.
Security considerations
⚠ Learning shortcut — not for production
Right-sizing by last-accessed alone is a shortcut: it cannot see calls that run less often than the tracking period, it works at service level for many services, and it says nothing about resources and conditions. In production combine it with Access Analyzer policy generation, an owner interview for rare jobs, non-production testing and a monitored staged rollout, and keep a break-glass path for emergencies.
- Never fix a broad role by adding a broader deny elsewhere without understanding the evaluation. Explicit denies override allows, which can break jobs in surprising ways. See Policy evaluation logic.
- Watch for privilege-escalation actions:
iam:PassRoleon*,iam:CreatePolicyVersion,iam:AttachRolePolicy,sts:AssumeRoleon broad resources,lambda:UpdateFunctionCode. A role that can change roles is effectively an administrator. - Fix the trust policy too. A narrow permissions policy with a trust policy that any principal in the account can assume is still weak.
- Do not store the generated policy blindly. Review it. It can contain resource ARNs that expose names of sensitive systems; treat it as internal.
- Change control. IAM changes to production roles follow your bank's change process, with security approval and a rollback plan. This playbook does not replace it.
- Audit trail. Record the evidence used (job IDs, dates, tool output), the reviewer, the approval and the date the old policy was removed.
Banking use case
Harbourline's reporting role ran daily jobs plus a quarter-end regulatory extract that read a second bucket and published to an SNS topic. The last-accessed data showed SNS last used 262 days earlier, which the tool flagged as stale. A blind cleanup would have removed it and broken the next quarter-end publication. The owner interview surfaced the job, the team kept sns:Publish on that one topic ARN with a comment citing the job, and removed sqs:*, kms:* on * and every wildcard action. The new policy went on alongside the old one for six weeks, through a month-end close, with an alarm on AccessDenied for the role. Nothing fired, the old policy was detached, and the change record held the evidence package for audit.
Common mistakes
- Removing permissions the same day with no staging. Permissions are additive, so attach the new policy first.
- Trusting a 30-day window for a role with quarterly or annual jobs.
- Treating policy generation as final. It is a draft: add conditions and check resources.
- Ignoring other policies. Permission also arrives through group-like patterns, permission sets, resource policies and boundaries; check them all.
- Leaving
iam:PassRoleon*while trimming everything else. - No rollback plan. Keep the old policy document so the revert is one command.
- Fixing the role but not the people. If developers cannot get a right-sized role quickly, they will ask for broad ones again. Provide a fast path and templates.
Troubleshooting
| Symptom | Likely cause | Fix |
|---|---|---|
| Last accessed shows nothing for a service you know is used | Tracking gap, regional endpoint, or a service without data | Cross-check with CloudTrail |
get-service-last-accessed-details returns IN_PROGRESS | Job not finished | Retry after a few seconds |
| Policy generation fails to start | CloudTrail trail or service access role missing permissions | Check the trail ARN and the access role's trust and S3 read access |
Generated policy full of * resources | CloudTrail lacked data events or resource detail | Hand-narrow resources, enable data events for next time |
Job fails after change with AccessDenied | Rare action not in the window | Read the denied action in CloudTrail, add it narrowly, note why |
| Simulator says allowed, reality denies | An SCP, boundary, session policy or resource policy denies | Check the other layers, see the AccessDenied playbook |
| Unused-access analyzer shows too many findings | Window too short or many dormant roles | Set an age that matches business cycles, triage by sensitivity |
| Role still too powerful after trimming | iam:PassRole or admin-like actions kept | Restrict them to specific role ARNs with iam:PassedToService conditions |
Cost and cleanup
Cost label: free for last-accessed data, policy generation and the simulator (⚠ VERIFY current pricing; Access Analyzer unused-access findings are a paid feature, so enable the analyzer in the sandbox only for a short test or skip it). The tool runs offline.
# Remove the sandbox analyzer if you created one
aws accessanalyzer delete-analyzer --analyzer-name hl-unused-access --profile learn-sandbox
# Remove sandbox roles and policies you created for the exercise
aws iam delete-role-policy --role-name hl-reporting-role --policy-name hl-reporting-narrow --profile learn-sandbox
aws iam delete-role --role-name hl-reporting-role --profile learn-sandbox
# Confirm nothing tagged for this lesson remains
aws resourcegroupstaggingapi get-resources --tag-filters Key=Lab,Values=m17-playbook-iam-broad --profile learn-sandboxExercises
- 🟢 Guided: Run the tool on the sample files. For each of the five services write down: keep, narrow or remove, and what you would ask the owner.
- 🟡 Challenge: Extend the tool to read action-level data from
TrackedActionsLastAccessed(where present) and list which individual actions were used, so the output proposes a concreteActionarray per service. Add a second input of "rare jobs" (a JSON file of service and action pairs) that are always kept. - 🔴 Live problem: "Audit wants
hl-batch-roleright-sized by Friday. It hasAdministratorAccess, is assumed by a nightly Step Functions workflow, and the CloudTrail trail only keeps 30 days online." Propose the plan, what you can and cannot conclude from 30 days, and how you contain the risk before Friday.
Assignment
Produce a right-sizing report for one role in your sandbox or capstone: inventory, evidence (last accessed, generated policy), the narrowed policy as CDK or Terraform, the must-allow and must-deny test list, the staged rollout plan with the monitoring query, and a rollback command. Commit it as reviews/iam-right-sizing-reporting-role.md with fictional identifiers.
Solutions
S3, DynamoDB and KMS: narrow, do not remove. They are used, so replace s3:*, dynamodb:* and kms:* with the exact actions from CloudTrail and specific resource ARNs, and add conditions such as kms:ViaService. SNS: ask the owner. It was last used 262 days ago, which is outside the 90-day window but may be a quarter-end or annual job. SQS: remove, never accessed in the tracking period, after confirming the owner has no disaster-recovery use. Why: unused and stale services need different handling, and the stale class is where outages hide.
For each service object read TrackedActionsLastAccessed (an array of objects with ActionName, LastAccessedTime, LastAccessedRegion). Collect the action names accessed within the window and print service:ActionName. Load the rare-job file into a HashSet<string> of service:action strings and union it into the proposed list, tagging each with the source ("observed" or "rare job"). Anything neither observed nor listed is dropped. Why: the proposal is then evidence-based and the exceptions are explicit and reviewable, not hidden.
With 30 days online you can only prove what happened in 30 days, so monthly and quarterly jobs may be invisible. First, check whether the trail also delivers to S3 with longer retention, because Athena over the S3 archive may cover far more than 30 days. Use last-accessed data (longer tracking period, ⚠ VERIFY) and the Step Functions state machine definition itself: the workflow's tasks list every service the role must call. Contain the risk before Friday by adding a permissions boundary or SCP that denies the dangerous actions (IAM changes, logging changes, key deletion), without changing what the workflow needs. Then attach a narrower policy built from the workflow definition plus evidence, run it in non-production, and keep AdministratorAccess attached until a full monthly cycle passes. Report to audit: ceiling in place now, narrow policy staged, removal date after validation. Why: a boundary reduces blast radius immediately with low outage risk, while the evidence for full right-sizing accumulates.
Knowledge check
Answer: IAM permissions are additive, so attaching the narrow policy changes nothing in behaviour. You can then monitor and detach the broad policy in a separate, reversible step.
Answer: Not without asking the owner. It may serve a quarterly or annual job outside the observation window. Investigate, then keep a narrow action and resource if needed.
Answer: A CloudTrail trail covering the period, with data events if you need object- or item-level detail, plus a service access role that can read the trail. It cannot know about activity outside the period.
Answer: iam:PassRole (or other IAM write actions) on *, because it allows escalating to a more powerful role even if every service permission was trimmed.
Answer: It sets an immediate ceiling over what the role can ever do, reducing blast radius while you collect evidence, and it does not itself grant permissions.
Interview questions
- How would you right-size an over-privileged role in production? Inventory, gather last-accessed and CloudTrail evidence, draft with policy generation, interview the owner for rare jobs, test, attach alongside, monitor a full cycle for
AccessDenied, then detach with a rollback ready. - What are the limits of last-accessed data? Limited tracking window, mostly service-level for many services, no resource or condition detail, and it cannot see rare jobs.
- How do you stop broad roles being created in the first place? Templates, code review with policy checks, Access Analyzer custom policy checks in the pipeline, SCPs and boundaries, and a fast path for least-privilege requests.
- What is the risk of using policy generation output unchanged? Wildcards, missing rare actions and no conditions, so it needs human review.
- What is the difference between a permissions boundary and an SCP? A boundary caps one role or user; an SCP caps every principal in an account or organisational unit.
Certification practice
A security team wants to generate a least-privilege policy for an existing role based on its actual API activity over the last 60 days. Which service feature should they use?
A. AWS Config conformance packs. B. IAM Access Analyzer policy generation using CloudTrail logs. C. Amazon Inspector. D. AWS Trusted Advisor.
Answer: B. Policy generation builds a draft policy from CloudTrail activity. Config packs evaluate configuration, Inspector scans for vulnerabilities, Trusted Advisor gives general checks.
An organisation has hundreds of roles with AdministratorAccess. They need an immediate guardrail that limits damage while teams work on right-sizing over months. What is the best first step?
A. Delete all roles. B. Apply an SCP denying high-risk actions (for example disabling logging, changing IAM) to the affected accounts, with a break-glass exception. C. Ask each team to fix their roles with no deadline. D. Rotate all access keys.
Answer: B. SCPs give an organisation-wide ceiling quickly with minimal breakage. A causes an outage, C leaves the risk, and D does not address permissions.
A pipeline should fail when a pull request adds an IAM policy granting *:*. Which approach is most appropriate?
A. Manual review only. B. Automated policy validation or custom policy checks (for example IAM Access Analyzer checks) in the CI stage. C. A weekly spreadsheet audit. D. Allow it and alert after deployment.
Answer: B. Automated checks in the pipeline prevent the change from deploying. Manual or after-the-fact approaches are slower and leave exposure.
Completion checklist
- I can list the three evidence sources and their blind spots
- I can describe the staged rollout and where the rollback is
- I ran the tool on the sample files and explained "stale" versus "never"
- I know why
iam:PassRoleon*defeats a trim - I can explain how a boundary or SCP buys time
- I ran the cleanup steps and confirmed nothing tagged
m17-playbook-iam-broadremains
Key takeaways
- Compare what is allowed with what has been done, then trim in a staged, reversible way.
- Attach the new policy before removing the old one, and monitor a full business cycle.
- Rare jobs hide outside the observation window: ask the owner.
- Policy generation drafts, humans add conditions and resources.
- Use a boundary or SCP as an immediate ceiling.
Further reading
- IAM Access Analyzer policy generation
- Refining permissions using last accessed information
- Previous playbook: S3 bucket accidentally public
- Next playbook: Slow SQL after migration to RDS
- Related: Module 17 overview
Independent learning resource — not affiliated with, endorsed or sponsored by Amazon Web Services. AWS and related marks are trademarks of Amazon.com, Inc. or its affiliates. All banking data in examples is fictional. Sample architectures are for learning and are not automatically compliant with GDPR, PCI DSS or any banking regulation.
Playbook: S3 bucket accidentally public
Contain an exposed S3 bucket in minutes with Block Public Access, work out who changed it and who read from it using CloudTrail and access logs, preserve evidence, and hand a factual timeline to the incident and data protection teams.
Playbook: slow SQL after migration to RDS
Find out why a query that was fast on-premises is slow on Amazon RDS by separating network round trips, plan and statistics changes, storage limits, parameter differences and connection-pool behaviour, using database insights, wait statistics and Query Store.