Policy as Code for CDK
Policy as code makes a checkable part of your architecture rules executable and versionable.
Policy as Code for CDK
If you only write an architecture rule down, sooner or later you get it back as an incident. No publicly readable bucket, every table encrypted, no instance larger than necessary, everything tagged: this list is rarely complete in one place. It exists in a few heads, in a wiki nobody opens anymore, and in review comments that depend on who happens to be looking and how much time they have. One inconspicuous default is enough, and the good intention turns into an open bucket in production. This problem is exactly what this post is about – and cloudpatrol is my attempt to solve it.
In my post about the early days of CDK, the text ends with a subordinate clause: for rules that are not negotiable, an automated check of the synthesized template is worthwhile, a kind of policy as code for your own CDK output. Here I make good on that clause. It is less about yet another tool than about running well-founded guardrails as automated checks. Trade-offs remain architecture work.
Why rules fall out of the review#
A review is a human with limited attention. Today they see that a bucket has no encryption, and next week they miss it because the pull request is big, it’s Friday afternoon or the interesting discussion was happening elsewhere. That is no accusation. That’s how attention works. Knowledge that only exists in the review is as reliable as the reviewer’s form on the day.
It follows that a rule you can’t execute is not a rule. It is a hope. As long as “no public bucket” is a sentence in the onboarding document, it will be broken at some point – not out of ill will, but because a default slips through unnoticed. The point of policy as code is therefore less technical than cultural. It moves the rule from a place where it has to be remembered to a place where it is checked.
The CDK is what makes this shift possible. Because infrastructure here is code that is synthesized into a CloudFormation template, there is an intermediate step you can inspect before anything is created in the cloud. This intermediate step is exactly the right place for a check.
The checkpoint lies between synthesis and deployment#
You can check cloud resources in many places. At runtime, a service that scans accounts finds violations only once they already exist. A weekly report is better than nothing but always comes too late for the person who made the mistake. It gets interesting when the check moves to where the decision is made: the moment the code generates the template.
flowchart LR Source["CDK code (TypeScript)"] --> Synth["cdk synth"] Synth --> Policy["Policy check"] Policy -->|violation| Fail["Feedback in the PR"] Policy -->|ok| Deploy["Deployment"]
cloudpatrol comes in at exactly this point. It hooks into synthesis and evaluates the constructs while they are being created. That is an architecturally different approach from a downstream scanner. The check doesn’t see the raw JSON template but the typed constructs with their properties. That way you can write a rule against s3.CfnBucket instead of matching a string path in a YAML tree. The boundary where the check happens is the same boundary the developer thinks in.
The effect on the cycle is concrete. A violation that used to become visible as an incident – someone reports an open bucket, there is an investigation, a fix, a postmortem – now becomes visible as a red test run before the pull request is merged. The time between error and detection shrinks from days to seconds, and the cost of the correction drops accordingly.
A policy is code, not a config entry#
The decisive design choice in cloudpatrol is that a rule is not a line in a YAML file but a class. It declares which construct type it applies to, and it contains a validator method that checks the concrete node and reports findings to a reporter.
import { Policy, PolicyInterface, Reportable } from "cloudpatrol";
import * as s3 from "@aws-cdk/aws-s3";
export class BucketEncryptionPolicy extends Policy implements PolicyInterface {
public policyName = "Bucket Encryption";
public description = "S3 buckets must be encrypted at rest.";
public scope = s3.CfnBucket;
public validator(node: s3.CfnBucket, reporter: Reportable): void {
if (!node.bucketEncryption) {
reporter.addError(node, this, "Bucket has no server-side encryption configured.");
}
}
}
The scope is the selector: the validator only runs for buckets, not for every node in the tree. Inside the validator, I have the full expressive power of TypeScript. I can nest conditions, allow exceptions for certain environments, evaluate several properties together. This is exactly where a declarative rule language hits its limit – the interesting rules are rarely “field X must be Y” but “field X must be Y, unless Z, and then please with this justification”.
The whole thing is applied via a patrol that walks through a stack:
const patrol = new AwsCdkPatrol(awsDefaults);
patrol.check(stack);
cloudpatrol comes with a handful of built-in policies – encryption, versioning, instance types – but the built-in ones are only the starting point. The real value emerges when a team translates its own unwritten list into such classes. From then on, the list is no longer unwritten. It lives in the repository, it is versioned, it has an author and a history, and you can discuss it in a pull request like any other code.
warn or block is a design decision#
Not every rule carries the same weight. A missing cost center tag is annoying; a publicly readable bucket with customer data is an incident. That’s why the severity of a rule is not a detail but the central design decision. A warning reports and lets things through. An error blocks. If you block everything, you train your team to work around the check. If you block nothing, all you end up with is nicely formatted log output.
Here I deliberately distinguish between guardrails and architecture police. Guardrails define the few boundaries that are truly non-negotiable: encryption, least privilege, no open networks, hard cost limits. Within these boundaries, the team stays able to act and stays fast. Architecture police, on the other hand, tries to centralize every decision and thereby shifts responsibility away from the teams. The first speeds up safe work; the second slows things down and frustrates. The difference lies not in the tool but in the question of how many rules you set to block and how well you justify those few.
type Severity = "warn" | "block";
type RuleMeta = {
policyName: string;
severity: Severity;
reason: string;
suggestion: string;
};
Every rule needs a reason and a way out#
A check that only says “forbidden” is a wall. The developer stands in front of it, doesn’t understand why and looks for the shortest way around it. A check that delivers the reason and an alternative is learning feedback. It explains the decision exactly where it becomes relevant and makes the next developer a bit more independent.
{
"policy": "lambda-timeout-max",
"severity": "block",
"reason": "A timeout above 30s usually hides a synchronous call that should be async.",
"suggestion": "Move the work behind a queue or a Step Function and return early."
}
These three fields – reason, severity, way out – are the difference between a rule that creates friction and one that reduces it. The reason prevents the rule from being read as arbitrary. The way out turns blocking into a recommendation. That’s exactly why every policy in cloudpatrol has a description and a link field: the rule carries its own justification with it instead of parking it in a wiki that is decoupled from the code.
The pull request is the right place#
Guardrails work best before deployment, and the pull request is the natural place for that, because that’s where code, context and discussion come together. In practice, this means the policy check runs in the same pipeline that builds the code and ships the infrastructure. A red check is then not a bureaucratic step but the same kind of signal as a failed unit test.
At this point the benefit is measurable, on three levels. First, cycle time: a violation becomes visible when the pull request is opened, not days later in operation. Second, consistency: the check is always equally strict, regardless of who reviews and how full their calendar is. Third, review load: people no longer have to mechanically search for the same ten things but can focus on the questions a machine can’t answer – does the cut of the stack make sense, does the abstraction fit, is the cost profile right.
That is the real productivity gain: a machine takes over the same boring checking work every time, and the minds on the team are freed up for the interesting work.
Costs are an architecture signal#
One side effect is worth mentioning because it is often overlooked. Cloud costs are not just a topic for accounting; they are a behavioral signal of the architecture. A function that starts too often, a resource that is sized too generously, a deployment that produces unnecessary artifacts – all of this leaves a cost trail before it gets named as an architecture problem.
flowchart LR Usage["Usage"] --> Cost["Cost trail"] Cost --> Signal["Signal"] Signal --> Rule["Policy as a guardrail"]
A policy that flags an overly generous instance type or a missing lifecycle rule is therefore not just a technical check. It catches a cost decision before it shows up as a bill next month. Costs don’t replace design, but they are an honest touchstone for whether the architecture behaves the way you assumed when designing it.
Where policy as code reaches its limit#
It would be a mistake to try to cast everything into a rule. Some decisions are not a check but a trade-off, and those belong to a human. A timeout above thirty seconds can be wrong or exactly right, depending on context. Such cases belong in an architecture conversation or a short ADR, not in a blunt blocker. The policy then doesn’t say “forbidden” but “this needs a justification”.
This gives policy as code a clear responsibility. It is suitable for the small set of non-negotiable guardrails whose violation is objectively recognizable. It is not suitable for matters of taste, nor for trade-offs where the right answer depends on the project. If you respect this boundary, you get a tool that creates trust. If you ignore it and turn every opinion into a blocking rule, you get a tool that gets bypassed.
A second caveat concerns abstraction. cloudpatrol checks what synthesis produces. A self-written construct that encapsulates a dozen resources can unintentionally undermine a rule if it sets the checked property differently than you think. So the check is only as honest as the visibility of the constructs. That is not an argument against abstraction, but a reminder that a rule and the building blocks it runs against have to be designed together.
What I take away after a few weeks#
cloudpatrol is alpha, the API is moving, and I wouldn’t build a big initiative on it today. But the direction convinces me, and it is independent of the specific tool. As soon as infrastructure is code, its rules belong in the same cycle as the code: versioned, checked, open to discussion in the pull request. The gain is not that a machine finds errors. The gain is that an architecture decision no longer lives in the head of a single person but sits in the repository as an executable, justified rule that another developer can meaningfully disagree with tomorrow.
Whether a rule is worth it comes down to three points. It has to prevent a real failure case that I can name, it has to deliver its reason, and it has to show a way out. If it does, the rule no longer depends on the reviewer’s form on the day but on a check that is always equally strict. Everything else remains a topic of conversation for humans – and that’s a good thing.
Further reading#
- AWS CDK, introduction and concepts: https://docs.aws.amazon.com/cdk/latest/guide/home.html
- Constructs as building blocks: https://docs.aws.amazon.com/cdk/latest/guide/constructs.html
- Policy as code for the CDK (cloudpatrol): https://github.com/MikeBild/cloudpatrol
Revised and translated from German with the help of AI.