Join our Newsletter — 33% off our NHI Course
Home› Guides› How to Write Least-Privilege IAM Policies From Access…
Guide Cloud & Workload Identity

How to Write Least-Privilege IAM Policies From Access Activity: Logs to Policy in Steps

PDF for newsletter subscribers · free to read online

← All guides
By NHI Mgmt Group, edited by Lalit Choda Updated 14 November 2026 15 min read
On this page

Service accounts and workloads usually run with permissions someone guessed at on day one, and nobody shrinks them later because nobody knows what the workload really calls. The answer is already in your logs: every cloud API call a workload makes is recorded with the caller, the operation and the resource. This guide sets out a repeatable method for turning that activity into a tight policy across AWS, Google Cloud, Kubernetes and Microsoft (Azure and Entra), including the gaps in each log source that cause generated policies to break production. It is written for cloud platform, IAM and NHI governance engineers who own service roles, service accounts, managed identities and app registrations. Platforms are listed alphabetically; the order is not a ranking.

Key takeaways

  • Logs record what happened, not what is needed. A policy built from 90 days of activity misses quarterly jobs, disaster recovery paths and error handling, so every draft needs an owner review against the workload's full business cycle.
  • Control plane logs are on by default, data plane logs usually are not. Reads of objects, secrets and table rows are often invisible until you turn on data event, Data Access or resource logging, which means generated policies omit exactly the permissions that touch sensitive data.
  • Collect first, then generate, then tighten scope. Turn on the right logging, observe for a full cycle, derive the action list, then replace wildcards and account-wide resources with specific ARNs, resource names and scopes.
  • Deploy beside, then swap, then remove. Attach the new policy alongside the old one in a test environment, watch for access denied errors, then remove the broad grant; keep the old definition for fast rollback.
  • Repeat on a schedule. Workloads change, so the logs to policy loop is a standing control with metrics, not a one-off clean-up.

Why activity-based policy writing works, and where it fails

The IDPro technique known as record then replace is the basis here: run the workload, record what it calls, build a role from that record and use it instead. The Least Privilege Techniques Guide explains the technique family; this guide is the hands-on version for machine identities across clouds. It works well for non-human identities because their behaviour is narrow and repetitive compared with a human administrator.

It fails in predictable ways, and the failures shape the method:

  • Observation window too short: generators and recommenders look back up to 90 days. A month-end batch, an annual certificate renewal or a failover runbook may not appear.
  • Invisible calls: data plane reads, some delegation actions and calls rejected before authorisation may never be logged.
  • Noise captured as need: denied attempts, exploratory calls during setup and a past misconfiguration are all in the logs and can end up in the draft.
  • Action without resource: logs give you the action list easily, but scoping each action to the right resource is manual work and is where most of the risk reduction sits.

The overprivileged firewall role in the Capital One breach could list and read many storage buckets that a firewall never needed. Activity-based right-sizing exists to find that gap between granted and used before an attacker does. See the OWASP NHI Top 10 NHI5 Overprivileged NHI Guide for the risk framing.

Log sources and their gaps by platform

Before generating anything, confirm the logs can actually see the workload. The table lists, for each platform, the source that records control plane activity, the source you must turn on for data plane activity, and the fields that identify the non-human caller.

PlatformControl plane sourceData plane source (turn on)Caller and operation fields
AWSCloudTrail management events in a trailCloudTrail data events, off by default and charged separately (for example S3 GetObject, Lambda Invoke, DynamoDB PutItem)userIdentity, eventSource, eventName, resources
Google CloudAdmin Activity audit logs, always writtenData Access audit logs, off by default except BigQueryauthenticationInfo (principal), methodName, serviceName, resourceName
KubernetesAPI server audit log at Metadata level or aboveSame log; requires an audit policy and a log or webhook backenduser.username (service accounts appear as system:serviceaccount:<namespace>:<name>), verb, objectRef
MicrosoftAzure activity log (control plane, kept 90 days); Microsoft Graph activity logs for Entra appsAzure resource logs through a diagnostic setting (for example Key Vault secret reads)Azure: caller and operation name in AzureActivity; Graph: AppId, ServicePrincipalId, RequestMethod, RequestUri, Roles

Two rules follow. First, turn on data plane logging for the specific resources the workload touches, scoped with selectors or filters to keep the cost reasonable, at least for the observation window. Second, export logs to a central store with retention longer than the window you plan to analyse. See the AWS CloudTrail Guide, Google Cloud Audit Logs and Log Sinks Guide, Azure Monitor, Activity Log and Diagnostic Settings and Kubernetes Audit Log Detection Guide for collection detail.

The logs to policy method, step by step

  1. Pick the identity and its owner. One service role, service account, managed identity or app registration at a time. Record the owner, the workload it serves and the business cycle (daily, monthly, annual tasks). Start with identities that hold admin, owner, editor or wildcard grants.
  2. Make the identity attributable. If several workloads share one identity, split them first; a shared identity produces a union policy that is least privilege for nobody.
  3. Turn on the missing logs. Add data plane logging for the resources the workload uses and confirm events arrive for a test call.
  4. Observe for a full cycle. Use at least 30 days for simple services and 90 days where monthly jobs exist; for annual tasks, ask the owner to run them in a test environment during the window or list them explicitly.
  5. Derive the action list. Use the platform's generator or recommender where one exists, and query the raw logs for the rest: distinct operation names grouped by the caller, filtered to successful calls.
  6. Separate success from denial. Treat denied calls as questions, not grants: either the workload genuinely needs the permission (add it deliberately) or it is a bug or probe (fix or investigate).
  7. Scope every action to resources. Replace * resources with the specific buckets, keys, queues, projects or resource groups seen in the logs, and add conditions (source network, tags, organisation membership) where the platform supports them.
  8. Add what the logs cannot see. Delegation permissions such as role passing or service account impersonation, rare runbook actions, and break-glass paths, each with a documented reason.
  9. Validate the draft. Run the platform's policy linter or validator, and check that no permission enables privilege escalation (for example creating keys for other identities or editing role bindings).
  10. Deploy beside the old policy in test, then production. Attach the new policy, remove the broad one in a test environment, watch denied errors for one cycle, then repeat in production during a change window.
  11. Keep rollback ready. Store the previous policy version so the owner can restore it in minutes; record the change ticket.
  12. Schedule the next pass. Re-run the analysis every quarter, or when the workload's release introduces new integrations.

Platform how-to

Each platform below gets the same four parts: where the usage signal comes from, how to build the policy, the gaps to fill by hand, and an availability note.

AWS

  • Usage signal: IAM Access Analyzer policy generation reads CloudTrail events for a user or role over a date range of up to 90 days. For some services, such as Amazon EC2, it lists the individual actions; for others it lists the services used, drawn from last accessed information, and prompts you to add actions. Last accessed information keeps service-level data for at least 400 days and action-level data for management actions in covered services. See the IAM Access Analyzer Guide.
  • Build: generate the template, replace the resource ARN placeholders with real ARNs, remove statements the role does not need, save it as a customer managed policy and attach it. AWS advises removing overly broad policies from the role once the new one is attached. Templates larger than the 6,144 character managed policy limit are split into several policies.
  • Fill by hand: add data event actions (for example s3:GetObject) from CloudTrail data events, because generation lists actions for management events; add iam:PassRole where the role passes roles, because CloudTrail does not track it; check denied actions, which generation reviews alongside allowed ones.
  • Availability: generation needs a trail for the account and a service role that can read its bucket; for an organisation trail in another account, set the bucket's object ownership to Bucket owner enforced and grant the service role read access. Trails managed by AWS Control Tower in the Log Archive account need a separate trail for this purpose. Data events carry additional CloudTrail charges and standard S3 request rates apply.

To find roles and keys to retire rather than right-size, use How to find unused AWS IAM roles and access keys.

Google Cloud

  • Usage signal: the IAM recommender compares each principal's granted permissions with those used in the last 90 days and produces policy insights (google.iam.policy.Insight) and role recommendations (google.iam.policy.Recommender). A machine learning model also suggests permissions the principal is likely to need but has not used recently, which softens the short window problem. For project-level recommendations the observation period can be set to 30 or 60 days; a newly granted role can take up to 15 days to receive an insight.
  • Build: review REMOVE_ROLE and REPLACE_ROLE recommendations, or REPLACE_ROLE_CUSTOMIZABLE, which proposes a new project-level custom role. Recommendations are never applied automatically; applying or dismissing one writes an audit log entry. For workloads outside the recommender's scope, query Admin Activity and Data Access logs for distinct methodName values per service account and map them to permissions in a custom role.
  • Fill by hand: the recommender analyses IAM bindings and leaves ACLs and Kubernetes RBAC to their own review; conditional role bindings get no insights; turn on Data Access logs so data reads are visible to your own queries. Act on lateral movement insights, which flag service accounts from other projects holding impersonation permissions such as iam.serviceAccounts.actAs. See How to Audit GCP Service Account Impersonation Rights.
  • Availability: recommendations for basic roles (Owner, Editor, Viewer) are free; recommendations for other roles, policy insights, lateral movement insights and custom role suggestions require Security Command Center Premium or Enterprise. Data Access logs add logging cost.

Start with How to Find GCP Service Accounts With Owner or Editor Roles to pick the first targets.

Microsoft (Azure and Entra)

  • Usage signal: for Azure resources, the activity log records control plane create, update, delete and action operations for 90 days; export it to a Log Analytics workspace (AzureActivity table) to analyse longer windows. For Entra app registrations and service principals that call Microsoft Graph, Microsoft Graph activity logs (MicrosoftGraphActivityLogs) record each request with AppId, ServicePrincipalId, RequestMethod, RequestUri and the Roles and Scopes in the token.
  • Build: for Azure, group successful operations by caller and operation name; the operation names correspond to RBAC action strings such as Microsoft.Compute/virtualMachines/restart/action. Put them in a custom role's Actions (control plane) and DataActions (data plane) and limit AssignableScopes to the subscriptions or resource groups seen in the logs. Microsoft recommends explicit actions over wildcards, because a wildcard also grants permissions added in future. For Graph, compare the application permissions in Roles with the endpoints actually called and move to the least privileged permission documented on each API reference page, for example User.Read rather than User.ReadWrite.
  • Fill by hand: reads are usually not in the activity log and data plane operations such as reading a Key Vault secret appear only in resource logs, so add a diagnostic setting for the resources in scope; requests rejected before an operation starts generate no entry, so test the draft role before swapping.
  • Availability: Microsoft Graph activity logs require a Microsoft Entra ID P1 or P2 licence and a diagnostic setting to Log Analytics, Storage or Event Hubs, with events delivered in most regions within 30 minutes. Log Analytics retention beyond 90 days is charged. A tenant can hold up to 5,000 custom Azure roles.

See the Azure RBAC and Service Principals Guide and the Azure Managed Identities Security Guide for the identity model.

Kubernetes service accounts

Kubernetes RBAC sits under all three clouds' managed clusters and needs its own pass. Configure an audit policy (audit.k8s.io/v1) that logs at least Metadata level for requests from service accounts, with the log backend (--audit-log-path) or webhook backend. Group events by user.username, verb, resource and namespace, then write a namespaced Role listing only those verbs and resources, with resourceNames where the workload touches named objects. Replace ClusterRole bindings with namespaced RoleBindings wherever the logs show single-namespace use. On managed clusters, collect the provider's control plane audit logs instead of setting flags. See the Kubernetes RBAC Guide.

Decision guidance

SituationApproachTrade-off
Simple, stable workload with daily behaviourGenerator or recommender output, 30 to 90 day window, scope resources, swapFast; low risk of missing rare actions
Workload with monthly, annual or failover tasksGenerated draft plus owner-listed runbook actions, tested in a staging runMore effort; avoids outages on the rare path
Shared identity used by several workloadsSplit into one identity per workload first, then right-size eachChange effort in code and deployment; the only way to reach least privilege
High-risk admin grant on a production identityRemove the admin grant quickly in favour of a broad but non-admin interim role, then refineTwo changes instead of one; cuts the worst exposure early
Hundreds of identities across cloudsPrioritise by privilege and exposure; consider a CIEM tool for cross-cloud usage analysisTool cost; native tools stay per-cloud. See the CIEM Buyers Guide

Small organisations: native generators, recommenders and log queries are enough; focus on the ten most privileged identities first. Large organisations: build the loop into the platform: new workloads start from a generated policy in pre-production, guardrails such as service control policies, organisation policies and Azure Policy cap what any grant can do, and a quarterly job reports drift between granted and used.

Detection and measurement

  • Access denied spike after a swap: alert on denials for the changed identity (CloudTrail errorCode AccessDenied, Google Policy Denied logs, Azure AuthorizationFailed, Graph 401 and 403 responses, Kubernetes 403 responses) for one cycle after each change.
  • New action from a right-sized identity: after the policy is tight, any new operation name from that caller is either a release or misuse; route it to the owner.
  • Metrics: percentage of NHIs with a policy derived from activity in the last 90 days; ratio of granted to used permissions per identity; count of identities holding wildcard actions or account-wide resources; median days from recommendation to applied change; rollbacks per quarter (should stay low and fall).

Framework mapping

FrameworkReferenceHow this method supports it
NIST SP 800-53 Rev 5AC-6 Least Privilege; AC-6(7) Review of User PrivilegesUsage-based reduction and periodic re-analysis of granted permissions
NIST SP 800-53 Rev 5AU-2 Event Logging; AU-12 Audit Record GenerationTurning on data plane and audit logging that the method depends on
NIST CSF 2.0PR.AA-05Permissions defined, managed, enforced and reviewed with least privilege
CIS Controls v8.16.8 Define and Maintain Role-Based Access ControlRoles built from documented, observed need
ISO/IEC 27001:2022 Annex AA.5.18 Access rights; A.8.2 Privileged access rightsProvision and review of access rights against need
MITRE ATT&CKT1078.004 Cloud AccountsLimits what a stolen cloud identity can do

Common failure patterns

  • Applying the generated policy unreviewed: it encodes whatever happened in the window, including denied probes and setup noise, and still carries placeholders or wildcards.
  • Window shorter than the business cycle: the month-end job fails on day 31 and the team restores the admin role permanently.
  • Data plane blind spot: without data event or Data Access logging the draft omits object and secret reads, so either production breaks or someone adds a wildcard to fix it.
  • Actions tightened, resources left open: a short action list on * resources still lets the identity read every bucket or vault in the account.
  • Shared identities: right-sizing an identity used by five services produces the union of all five and hides misuse inside legitimate traffic.
  • One-off clean-up: permissions grow back within two release cycles when no recurring job measures drift.

Practitioner checklist

  • List NHIs with admin, owner, editor or wildcard grants, with an owner for each.
  • Split shared identities so each workload has its own.
  • Turn on data plane logging for in-scope resources and confirm events arrive.
  • Observe for a full business cycle, 30 to 90 days or longer with runbook testing.
  • Generate or query the action list, filtered to successful calls; review denials separately.
  • Scope every action to specific resources and add conditions.
  • Add delegation, rare runbook and break-glass permissions with documented reasons.
  • Validate, deploy beside the old policy in test, then swap in production with rollback ready.
  • Alert on access denied and on new operations from right-sized identities.
  • Re-run the analysis quarterly and report the granted to used ratio.

Standards and references

Related NHI Mgmt Group resources: Least Privilege Techniques Guide · IAM Access Analyzer Guide · OWASP NHI Top 10 NHI5 Overprivileged NHI Guide · NHI lifecycle automation

PDF for subscribers

Take this guide with you

Every section, table and checklist in one PDF, with links to the sources and related guides. Subscribe to our weekly NHI & AI Identity Journal and we’ll email you a download link.

Free weekly newsletter

Subscribe to the NHI & AI Identity Journal

The latest on NHI and Agentic AI security – articles, research, breaches, news and events every week.

Bonus 33% off our NHI Course when you subscribe.

NHIMG Editorial Note
Researched and written by the NHI Mgmt Group editorial team using AI tools, under the editorial direction of Lalit Choda. Facts are drawn from the sources listed on this page and checked by our automated quality process. Last updated 14 November 2026. Spotted an error? Use our contact page.
NHI Mgmt Group, the independent authority on Non-Human Identity, IAM and Agentic AI security. nhimg.org

PDF Downloads for Newsletter Subscribers

Get the guide

Enter your details and we’ll email you a download link.

The full guide is free to read online. The PDF is a thank you for subscribing.

Fill in all fields marked * and tick the PDF box to continue.