// Why this matters
Cloud Custodian on AWS turns compliance rules into code that acts at the moment of the violation. A quarterly audit tells you that a bucket was unencrypted for six weeks. A policy in CloudTrail mode fixes it seconds after the API call and tells the person who did it.
Most teams already have the rules: tag everything with an owner, encrypt storage, never expose management ports to the internet, require MFA. What they lack is enforcement that does not depend on a human reading a report. Policy-as-code makes the rules reviewable, testable and version controlled, like any other change.
This post describes the policy library I built for a freelance client, generalised. It deliberately starts with safe actions (tagging, notification, reports) and builds toward remediation, because a governance tool that breaks production on day one gets switched off on day two.
// The problem
Periodic scans find problems late and generate tickets that nobody owns. By the time a report lands, the resource is in use, the author has moved on and fixing it risks an outage. Detection without attribution is mostly noise.
Attribution itself is a gap: AWS resources do not record who created them unless you tag them, and creators rarely do. Without an owner tag you cannot notify, charge back or clean up.
Scale is the third problem. Dozens of accounts across several regions mean the same rule must be deployed many times with different roles and settings. Hand-copying policies guarantees drift, and an account missed is an account with no protection.
// The solution
Cloud Custodian expresses each rule as a policy with four parts. The resource says what to look at, the mode says when (a periodic Lambda, a CloudTrail event, a config change or a one-off pull), filters select the offenders and actions fix or flag them. In CloudTrail mode the tool deploys a Lambda and an EventBridge rule, so remediation latency is the event delivery time and there is no scanner to run.
The policy set has four members. Instance auto-tagging runs on RunInstances and applies a creator tag with the principal from the event. Bucket encryption runs on CreateBucket and enables default encryption if absent. The security-group policy runs on the ingress authorisation and revocation events and removes any rule that opens a sensitive port to the whole internet. The MFA policy is a report, not an action, because disabling a human user is not something to automate blindly.
Notifications go through c7n-mailer. A policy notify action drops a message on an SQS queue; the mailer Lambda renders a template and emails the target, which can be the event owner resolved from the CloudTrail identity. The notification is the point at which a technical control becomes a social one: the person who opened the port learns why it closed.
For many accounts, c7n-org takes an accounts file (account IDs, a role to assume in each, a list of regions) and runs a policy file against all of them. Policy files use a templated {account_id} so a role ARN works everywhere. I rejected a central admin role with broad permissions in favour of one narrowly scoped role per account. For the equivalent on the platform side, see Automated IAM Compromise Detection and Credential Revocation and Guardrails and Engineering Telemetry: Org Policy, Project Factory, Gatekeeper, Four Keys.
- Policy YAMLresource, mode, filters and actions per rule
- CloudTrail modeLambda and event rule provisioned for key API events
- Filtertag absent, encryption off, open ingress, MFA inactive
- Action gateauto-tag, set encryption or remove the rule
- Notifymailer emails the offending user via SQS
- Multi-accountaccount lists and all-region variants
- Reportingreport policies and a control mapping
// Before you start
- Python 3.9+ and a virtual environment;
pip install c7n c7n-mailer c7n-org. - An AWS account with CloudTrail enabled for management events in each region you protect.
- An IAM role per account for the Custodian Lambdas, and an assumable role per account for c7n-org.
- An SQS queue for notifications and a verified sender address in SES.
- A sandbox account to test every policy in dry-run before enforcing it.
// Step-by-step implementation
01 Install the tools and prove them with a read-only policy
Create a virtual environment and install the three packages. Start with a pull-mode policy that only lists things. It proves credentials and region handling before any Lambda is deployed.
Use
--dryrunon everything that has an action until you have read the matched resources and agree with them.02 Auto-tag instances with their creator
This policy runs on
RunInstances. The filter limits action to instances with no creator tag, so it never overwrites.auto-tag-userreads the identity from the CloudTrail event and writes the tag; the principal-id tag helps when the name is an assumed-role session.Use the
{account_id}placeholder in the role ARN. When the policy is provisioned Custodian substitutes the account, so one file serves every account.03 Enforce default encryption on new buckets
Run on
CreateBucket, find buckets without default encryption and enable it. Chain the same tag action so the bucket also has an owner. The filter is idempotent: a bucket that already has encryption does not match, so replays are harmless.Use AES256 for a no-key-management baseline, or switch to KMS with a key ARN when policy requires customer keys.
04 Remove world-open ingress and tell the person who did it
Listen for ingress and egress changes on security groups. The
idsexpression tells Custodian where in the event to find the group, because the resource ID is not at the top level. The filter matches rules that expose sensitive ports to the whole IPv4 or IPv6 internet;remove-permissionswithmatchedremoves only the offending rule, not the whole group.Then notify. The
tolist can includeevent-owner, which Custodian resolves from the CloudTrail identity. Roll this out with notify only first, observe the matches for a week, then add the removal.05 Report users without MFA instead of acting on them
Not every control should be automated. An IAM user without MFA is a finding for a person to resolve, so this policy runs in pull or periodic mode, writes a report and, if you like, notifies the user. The credential report filter reads
mfa_activefrom the account credential report.Schedule it with a periodic mode and a cron expression, and keep the output in a bucket for audit evidence.
06 Deploy the mailer that turns queue messages into email
The mailer is its own Lambda that polls the SQS queue and sends through SES. Its config names the queue, the role it uses and the sender. Deploy or update it with the mailer CLI, then provision policies. Keep the sender address on a verified domain.
07 Roll out across accounts and regions with c7n-org
Write an accounts file with the account ID, a name, the regions to cover and a role to assume. Generate it from your organisation listing rather than by hand, and keep IDs out of source control if the repository is public. A region list per account lets you cover every enabled region for sensitive policies and a single region for cheaper ones.
Run with the
-uflag to use a specific policy file and dry run first. c7n-org fans the run out in parallel and writes output per account and region.
// How to verify it works
- In a test account, create a bucket without encryption: within seconds
aws s3api get-bucket-encryptionshows AES256 and the bucket has a creator tag. - Launch an instance with no tags: it gains
CreatorNameshortly after, set to the identity that launched it. - Add an ingress rule for port 22 from 0.0.0.0/0: the rule disappears and the author receives an email.
aws lambda list-functions --query "Functions[?starts_with(FunctionName,custodian-)].FunctionName"lists a function per CloudTrail-mode policy.- The MFA report shows the expected users and the mailer queue drains.
// Design decisions and trade-offs
- Remediation at event time rather than periodic scans.
- Notification is attributed to the actor who made the change.
- Account identifiers are templated, not hardcoded.
// Pitfalls and lessons learned
- A remediation that terminates or deletes is a different risk class from tag or notify. Start with notify, run dry, review matches, and only then remove or terminate.
- Event ids differ per event type. Without the correct
idsexpression a security-group policy runs and matches nothing. - Ports versus OnlyPorts in ingress filters change what matches. Test with a deliberately bad rule before trusting the policy.
- CloudTrail mode needs a trail delivering management events in that region, and events arrive with a short delay. It is fast, not instantaneous.
- Account lists with real IDs and role names should not live in a public repository. Template or generate them at run time.
- Auto-tagging overwrites if the filter is missing. Always filter on tag absent so you never replace a human-set owner.
// Frequently asked questions
How does Cloud Custodian CloudTrail mode work?
The tool provisions a Lambda and an EventBridge rule for the events you list. When one of those API calls is recorded, the Lambda runs the policy against the resource in the event.
How do I notify the person who created a resource?
Use the notify action with the event-owner recipient and an SQS transport; deploy c7n-mailer to read the queue and send email through SES.
How can I run policies across many AWS accounts?
Use c7n-org with an accounts file listing IDs, a role to assume per account and regions, and keep role ARNs templated with the account placeholder.
Should I auto-remediate everything?
No. Automate reversible, low-risk fixes such as tagging and encryption. Reports and notifications suit controls where a human decision is needed, such as disabling a user.
How do I test a policy safely?
Run it with the dry-run flag in a sandbox account, inspect the matched resources file, then provision it and trigger the event deliberately.
// The outcome
Policy violations fixed within seconds of the API call that caused them.
// Where to take it next
- Add tag-compliance policies that mark non-compliant resources for a later action with a grace period.
- Ship the Custodian run output to a bucket and build a compliance dashboard from it.
- Move the policy files into a repository with pull-request review, as in Vault Access via Directory Groups, Requested by an Agent, Approved by a Human.
- Combine with event-driven response for credential compromise from Automated IAM Compromise Detection and Credential Revocation.