Join our Newsletter — 33% off our NHI Course
Home› Guides› Cloud Custodian Guide: Policy-as-Code Guardrails and Auto-Remediation in…
Guide Cloud Security

Cloud Custodian Guide: Policy-as-Code Guardrails and Auto-Remediation in Cloud

PDF for newsletter subscribers · free to read online

← All guides
By NHI Mgmt Group, under the editorial direction of Lalit Choda Updated 27 November 2026 12 min read
On this page

Cloud estates drift out of policy faster than people can review them, and the tools that fix drift automatically can do serious damage if they are wrong. Cloud Custodian is an open source rules engine that lets teams write security and governance guardrails as YAML policies and run them against AWS, Azure, Google Cloud and other providers, either on demand or in response to cloud events. This guide explains how policies are built, which execution mode to pick, how to start in report-only mode, and how to run the Custodian identity itself with least privilege, because a remediation runner is one of the most powerful non-human identities in a cloud account. It is written for cloud security and platform engineers.

This is an independent guide from NHI Mgmt Group, based on Cloud Custodian's public documentation as of November 2026. It is not sponsored or reviewed by the Cloud Custodian project. Product features change, so confirm settings against Cloud Custodian's current documentation.

Key takeaways

  • Policy equals resource, filters, actions: every Custodian policy names a resource type, narrows it with filters and optionally applies actions; a policy with no actions only reports.
  • Mode decides when it runs: pull mode runs from the CLI or a pipeline, while event and periodic modes deploy the policy as a serverless function that reacts to cloud events or a schedule.
  • Dry run first, always: custodian run --dryrun evaluates filters without executing actions, so every new policy should prove its match set before it is allowed to change anything.
  • Prefer reversible actions: tag, notify and mark-for-op give owners time to respond; reserve stop, delete and policy-removing actions for well-tested, narrowly filtered cases.
  • The runner is a privileged NHI: scope separate read and remediation roles per account, keep policies in reviewed source control, and log every action Custodian takes.

What Cloud Custodian is

Cloud Custodian (package name c7n) is a Python application, licensed under Apache 2.0, that queries cloud resources, filters them against rules and takes actions on the matches. The project README describes support for AWS, Azure and GCP environments, and the installation docs list separate packages for each provider: c7n (includes AWS), c7n-azure, c7n-gcp and c7n-oci. It runs on Linux, macOS and Windows, or from the cloudcustodian/c7n container image.

  • Project status: the CNCF project page lists Cloud Custodian as an Incubating project, accepted to the CNCF on 25 June 2020 and moved to Incubating on 14 September 2022 (checked November 2026).
  • Where it fits: Custodian is a detective and corrective control that acts on resources after they exist. It complements preventive controls such as organisation policies and infrastructure-as-code checks, and posture management tools that score findings. For the wider picture see the Cloud Security Posture Management (CSPM) Guide.
  • Companion tools: c7n-org runs policies across many AWS accounts, Azure subscriptions, GCP projects or OCI tenancies in parallel, and c7n-mailer delivers notify actions by email, Slack and other channels from a queue.

Custodian is different from authorisation policy engines that decide on requests at runtime; if that is your goal, see the Policy-as-Code for Authorisation Guide.

Policy structure: resources, filters, actions

A policy file holds a list of policies. The getting started guide describes the three essentials: the type of resource to run against, filters to narrow the set, and actions to take on what remains. The example below is non-destructive: it finds S3 buckets that grant cross-account access and only tags and reports them.

1 Sample only, based on the public documentation cited. Assess it independently against the current official documentation, test outside production and back up first.

Sample 1
policies:
  - name: s3-cross-account-report        # unique name; also the output folder name
    resource: aws.s3                      # resource type (custodian schema aws lists them)
    description: |
      Report S3 buckets whose bucket policy grants access to other accounts.
    filters:
      - type: cross-account               # built-in filter for external principals
    actions:
      - type: tag                         # reversible: adds a tag, changes no access
        key: c7n-finding
        value: cross-account-access
      - type: notify                      # sends a message via c7n-mailer
        template: default
        subject: "S3 bucket shares data with another account"
        to:
          - resource-owner                # resolved from owner tags by the mailer
        transport:
          type: sqs
          queue: https://sqs.eu-west-2.amazonaws.com/111122223333/c7n-mailer

Run custodian schema aws.s3.filters.cross-account to confirm the exact options your installed version supports before adding optional keys, such as a list of approved partner accounts.

ElementWhat it doesSecurity notes
resourceSelects the resource type, such as aws.ec2, azure.vm or gcp.instanceUse the fully qualified provider prefix so intent is clear in review
filters (value)Generic JMESPath comparisons with operators such as equal, in, contains, regex and greater-thanTest edge cases: missing keys and case differences change the match set
filters (typed)Resource-specific checks such as cross-account, ebs encryption or is-log-targetSome typed filters are API heavy; the docs flag is-log-target as unsuitable for Lambda in large accounts
filters (boolean)or, and and not blocksNested logic is the most common source of over-broad matches
actionsTag, mark-for-op, notify, webhook, stop, delete, remove-statements and many resource-specific actionsAbsent actions means report only
conditionsLimits where a policy applies, for example by regionUseful to pilot a policy in one region first
modeDefines how and when the policy runs (next section)Event modes need an execution role

Execution modes: pull, event, periodic

The mode block decides whether a policy runs once from where you invoke it or is deployed as a function in the cloud. The Lambda documentation notes that the only difference between a policy run in Lambda and one run from the CLI in pull mode is the event subscription in the mode block.

ProviderModeTriggerTypical use
Allpull (default when no mode is set)CLI, CI job or scheduler you controlAudits, reports, dry runs, bulk clean-up
AWScloudtrailCloudTrail API calls delivered through EventBridge, within seconds at P99 per the docsReal-time response to risky API calls such as RunInstances or bucket policy changes
AWSec2-instance-state, asg-instance-stateInstance or Auto Scaling state changesChecks on instances as they launch
AWSperiodic, scheduleEventBridge rule or EventBridge Scheduler on a rate or cronDaily posture sweeps inside the account
AWSconfig-rule, config-poll-ruleAWS Config evaluations, typically 1 to 15 minutes per the docsCompliance reporting through AWS Config
AWSguard-duty, hub-finding, phdGuardDuty findings, Security Hub findings, Personal Health Dashboard eventsResponding to detections and service events
Azureazure-event-grid, azure-periodicSubscription write and delete events through Event Grid, or a CRON timerReal-time or scheduled checks run as Azure Functions
Google Cloudgcp-audit, gcp-periodic, gcp-sccCloud Audit Logs events, a schedule, or Security Command Center findingsReal-time, scheduled or finding-driven checks run as Cloud Functions

Choosing a mode

  • Start in pull: pull mode keeps the runner outside the account, makes dry runs trivial and fits a CI pipeline. It is the right starting point for every new policy.
  • Move to event modes for high-risk changes: public exposure, disabled logging or new cross-account trust are worth a near real-time response. Event filters can be narrowed with an EventBridge pattern under mode, so the function is not invoked for irrelevant events.
  • Use periodic modes for sweeps: drift that matters within a day (untagged resources, idle keys) does not need per-event functions.
  • Know the clean-up rule: the docs warn that switching a deployed policy between periodic and schedule modes does not remove the old rule; the project's mugc.py tool removes functions that no longer exist in your policy files.

Security guardrail examples

Good first guardrails are ones where the risk is clear and a false positive is cheap. The following patterns are drawn from the project's documented filters and examples; begin each as report only.

  • Cross-account storage access: the cross-account filter on aws.s3 with tag and notify actions, as above. The getting started guide shows the remediating form using remove-statements with statement_ids: matched, which should follow only after a review period.
  • Unencrypted volumes at launch: an ec2-instance-state or cloudtrail policy on RunInstances with an ebs filter on Encrypted: false. The docs example terminates the instance; a safer start is mark and notify.
  • Tag compliance with grace period: the documented three-policy pattern marks non-compliant instances with mark-for-op (for example op: stop, days: 4), a second policy unmarks resources that are fixed, and a third acts on resources whose date has arrived.
  • Risky identity configuration: report IAM users with old access keys or without MFA, and long-lived service account keys in Google Cloud, feeding the owners' queue rather than deleting credentials automatically. See the Google Cloud IAM and Service Accounts Guide.
  • Logging integrity: report when audit trails or diagnostic settings are disabled, and route the notification to the security team rather than resource owners.

Safe auto-remediation

Auto-remediation earns trust slowly and loses it in one incident. Roll it out in phases.

  1. Validate: run custodian validate policy.yml in CI on every change (validation also runs by default on run).
  2. Dry run: run custodian run --dryrun -s out policy.yml. No actions execute; review the matched resources written to the output directory and confirm every match is intended.
  3. Report only in production: deploy with no actions, or with tag and notify only, for at least one review cycle. Track how many matches owners dispute.
  4. Grace period: switch to mark-for-op so owners get a dated warning before anything changes.
  5. Narrow enforcement: enable the corrective action for one account or region using conditions or c7n-org account tags, then widen.
  6. Rollback: keep the previous policy version in source control, prefer actions that can be undone (tags, stop rather than terminate, statement removal that is logged), and know how to disable a deployed function quickly: comment out the policy and run mugc.py, or remove the trigger.
Action classExamplesReversible?Use when
Informnotify, webhookYes, nothing changesAlways first; ownership routing
Labeltag, mark-for-opYesGrace periods, reporting, staged enforcement
Containstop, remove-statements, security group changesMostly, with careHigh-risk exposure with narrow, proven filters
Destroyterminate, deleteNoRarely; only for disposable resources with explicit owner agreement

Running at scale and governance

The Custodian identity is a powerful NHI

Whatever runs Custodian holds read access to everything it evaluates and write access to everything it may remediate. An attacker who takes over that identity, or who can change the policy files it executes, gains a ready-made tool to modify every account in scope (ATT&CK T1078.004 Cloud Accounts). Treat it accordingly:

  • Separate roles: a read-only role for pull-mode audits and dry runs, and a separate remediation role whose permissions cover only the actions your policies use. The project's quick start provides an example IAM policy and states that customised IAM policies are needed for your own policies.
  • Per-account roles, short sessions: c7n-org assumes a role in each account from its config file; use workload identity or role assumption rather than long-lived keys. Google Cloud supports service account impersonation through GOOGLE_IMPERSONATE_SERVICE_ACCOUNT or --assume. The Azure Functions documentation describes service principal credentials for deployed functions; store any secret in a managed secret store and rotate it.
  • Boundaries: apply permissions boundaries or equivalent guardrails so the remediation role cannot grant itself more. See the AWS IAM Permissions Boundaries Guide and the Cloud Workload Identity Guide.
  • Protect the policy supply chain: policies live in a repository with branch protection and mandatory review, and the pipeline that deploys them is the only path to production.

Observability

Custodian writes per-policy output (logs and the resources matched) to a local directory or S3. With --metrics aws it publishes CloudWatch metrics including ResourceCount, ActionTime, ApiCalls and PolicyException, and --log-group streams logs to CloudWatch Logs, which can be centralised to a management account. The docs recommend a log subscription on the group to catch operational issues and S3 as the long-term archive.

Measuring it

  • Share of accounts, subscriptions and projects covered by the baseline policy set.
  • Median time from a matched resource to owner fix, before and after notifications.
  • Disputed or false-positive matches per policy per month (target: falling).
  • Number of remediation actions executed, with zero unplanned destructive actions.
  • PolicyException count and failed function invocations (target: zero unresolved).

Framework mapping

FrameworkReferenceHow Custodian supports it
NIST CSF 2.0PR.PS-01, DE.CM-09, ID.AM-02Enforcing configuration baselines, monitoring cloud runtime, resource inventory output
NIST SP 800-53 Rev 5CM-6, CM-3, CA-7, CM-8, AC-6Configuration settings, change control of policies, continuous monitoring, component inventory, least privilege for the runner
MITRE ATT&CK v20T1530, T1078.004Exposed storage that guardrails detect; abuse of the cloud account Custodian itself runs as

Common failure patterns

  • Skipping the dry run: a nested or block matches far more than intended and a delete action runs across production.
  • One admin role for everything: the same broad role does audits, remediation and deployment in every account, so one leaked credential or edited policy reaches the whole estate.
  • Orphaned functions: policies removed from the repository leave Lambda functions and rules running because no clean-up step exists.
  • Notifications nobody owns: owner tags are missing, mail goes to a shared inbox and findings age without action.
  • Silent failures: API throttling or permission errors stop a policy and nobody watches PolicyException metrics or function errors.

Practitioner checklist

  • Store every policy in a reviewed repository and run custodian validate in CI.
  • Run every new or changed policy with --dryrun and review the matched resources before deployment.
  • Start production policies as report only, then move to mark-for-op grace periods before corrective actions.
  • Create separate read-only and remediation roles per account, scoped to the actions in use, with boundaries.
  • Use role assumption, impersonation or workload identity instead of long-lived keys for the runner.
  • Enable metrics and centralised logs, and alert on policy exceptions and function errors.
  • Include mugc.py or an equivalent clean-up step in the deployment pipeline.
  • Review the policy set and runner permissions quarterly and confirm the CNCF and release status of the version you run.

Standards and references

Related NHI Mgmt Group resources: Cloud Security Guide · Cloud Security Posture Management (CSPM) Guide · AWS IAM Policies and Roles Guide · Cloud Resource Tagging Standard Template

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.

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 both boxes to continue.