Policy-as-code and secure deployment
Scan templates and plans before anything is deployed with cdk-nag, CloudFormation Guard, cfn-nag and Checkov, give pipelines least-privilege deploy roles, and stop a plan from deleting a database with a small C# guard.
Assumes: .NET 10 LTS · xUnit v3 4.0.3 · Amazon.CDK.Lib 2.277.0 · Cdklabs.CdkNag 3.0.2 · Terraform 1.17.2 · AWS CLI v2 · Region us-east-1. Verified against official sources on 2026-11-18.
Learning objectives
By the end of this lesson you can:
- Explain where policy checks run in the life of a change (editor, pull request, plan, deploy) and what each layer can and cannot catch.
- Write a CloudFormation Guard rule file, run Checkov on Terraform and a plan, and run cfn-nag on a template.
- Use cdk-nag v3 in a CDK (C#) app, read a finding and acknowledge it with a recorded reason.
- Design least-privilege deploy roles: a read-only plan role, a narrow apply role, and the CDK bootstrap roles with a customer-managed execution policy and permissions boundary.
- Protect stateful resources with
DeletionPolicy,UpdateReplacePolicy, termination protection, stack policies,prevent_destroyand service deletion protection. - Build and test a plan guard in C# that blocks a Terraform plan if it deletes or replaces a database, bucket or key.
Prerequisites
- Terraform fundamentals: reading a plan, especially
-/+lines. - Environment configuration and versioning: the promotion pipeline these checks plug into.
- Pipeline security scanning and Boundaries, SCPs, RCPs and resource policies.
- The CDK testing and cdk-nag lesson earlier in this module (start from the module overview), and CloudFormation fundamentals for change sets and deletion policies.
- Tools: Docker Desktop. No AWS account is needed for the scans and tests.
Why this matters in banking
Two incidents, both avoidable.
In the first, an engineer opens a pull request that "tidies" a database resource. The reviewer sees a small diff. The generated plan, which nobody opens, says -/+ destroy and then create replacement for the production database because the change touched an argument that cannot be updated in place. The pipeline applies it automatically. The data is gone; recovery means restoring a snapshot and explaining the gap to the regulator.
In the second, the pipeline's deploy role is AdministratorAccess. A compromised build runner uses it to create an IAM user with access keys in the production account. The IaC was perfect; the identity that ran it was the weakness.
Policy-as-code and secure deployment address both. You write rules once, run them on every change before apply, and give the pipeline only the access it needs, so a bad change or a stolen token has a limited blast radius. None of this makes you compliant with a standard. It produces repeatable controls and evidence that your compliance team can use.
The idea in plain language
Policy-as-code means your rules ("buckets are encrypted", "databases have deletion protection", "no security group opens SSH to the world") are written as machine-checkable code and run automatically, like unit tests for your infrastructure.
There are four moments to check, and you want most of them:
- While you type. Editor plugins and pre-commit hooks. Fast, advisory.
- In the pull request. The scanner reads the code or the synthesised template. Blocks the merge.
- On the plan. The scanner reads what is about to change, including deletes and replacements. Blocks the apply.
- At deploy time and afterwards. CloudFormation Hooks, SCPs and AWS Config rules refuse or flag resources even if someone bypassed the pipeline.
Analogy: think of building control. The architect's checklist (editor and PR checks) catches drawing errors. The inspector reviews the final plans before work starts (plan checks). The site foreman has a locked tool store, so only the right trades can touch the dangerous equipment (least-privilege roles). And the council can still stop work on site if something non-compliant gets built anyway (hooks, SCPs, Config).
What problem the tools solve
| Tool | Input | Language | Best at | Watch out for |
|---|---|---|---|---|
| cdk-nag | CDK construct tree during synth | Rule packs in code; acknowledgments in C# | Fast feedback in a CDK app; rule packs such as AWS Solutions | Only checks CDK apps; findings can be noisy on helper constructs |
CloudFormation Guard (cfn-guard) | Any JSON or YAML (templates, Terraform plan JSON) | Guard DSL | Custom bank rules you own; also usable as a CloudFormation Hook ⚠ VERIFY | You write and maintain the rules |
| cfn-nag | CloudFormation templates (including CDK output) | Ruby rule set, Metadata for suppressions | Quick lint of templates for common security smells | Smaller rule set; confirm the project is still actively maintained ⚠ VERIFY |
| Checkov | Terraform code, Terraform plan JSON, CloudFormation, and more | Python, many built-in checks, custom checks | Broad coverage with a large built-in policy library | Many checks flag "best practice" items; tune and record skips |
| Plan guard (this lesson) | terraform show -json plan | Your own C# | Blocking destructive changes to stateful resources | Only knows what you teach it |
| SCPs, Config rules, Control Tower controls | Live AWS account | JSON / managed rules | Safety net even if the pipeline is bypassed | Detects or denies late; see the landing-zone lesson |
Honest limitations:
- Scanners find known patterns, not intent. A bucket can pass every check and still hold data it should not.
- They can disagree. Two tools may flag the same issue under different IDs or only one may flag it. Pick a primary tool per language and use the others for coverage.
- Rules need owners. A rule nobody maintains becomes a pile of suppressions.
- Suppressions are risk acceptances. Each one needs a reason, an owner and, ideally, an expiry.
Microsoft / Azure comparison
| You know (Microsoft/Azure) | AWS / IaC equivalent | What's different |
|---|---|---|
| Azure Policy (deny, audit, modify) | SCPs and RCPs (deny), AWS Config rules (detect), CloudFormation Hooks and Control Tower proactive controls (block at provisioning) | Azure Policy is one engine; AWS splits the jobs across services |
| Azure Policy "what-if" compliance for templates | cdk-nag, cfn-guard, Checkov on the template or plan before deploy | You run these in CI; AWS does not do it for you |
| Microsoft Defender for DevOps / IaC scanning | Checkov, cfn-nag, cdk-nag, plus Amazon Inspector for what is already running | Mostly open-source tools you add to the pipeline |
| Service principal for deployments, with a custom role | A pipeline IAM role assumed by OIDC, with a narrow policy and a permissions boundary | Short-lived credentials via role assumption; no stored secret |
| Resource locks (CanNotDelete) | DeletionPolicy: Retain, termination protection, stack policies, prevent_destroy, service deletion protection | Several layers, each protecting a different path |
Architecture
Security-boundary view. There are two roles. The plan role can read the account and read and lock state but cannot create or delete anything. The apply role can change only what this stack manages, can be assumed only by the pipeline from the main branch or a release tag and only after approval, and cannot create IAM entities without a permissions boundary. SCPs sit above both and cannot be overridden from inside the account.
Step-by-step implementation
Add cdk-nag to the CDK app
Register the AWS Solutions rule pack on the app so cdk synth fails on unacknowledged findings. Acknowledge each remaining finding with its exact ID and a reason a colleague would accept.
Scan the synthesised template and Terraform code
Run cfn-guard with your bank's rule file on the template, cfn-nag for a second opinion, and Checkov on the Terraform folder.
Scan the plan, not only the code
Create the plan, convert it to JSON and run Checkov in plan mode and the C# plan guard. Code scans cannot see the replace-versus-update decision; the plan can.
Split the pipeline identity into plan and apply roles
The plan job gets a read-only role. The apply job gets a narrow role, only after approval. Neither is AdministratorAccess.
Protect the stateful resources in layers
Retain policies on stacks, prevent_destroy and deletion protection on databases, termination protection on the stack, and a stack policy for the one resource you must never replace.
Add a safety net outside the pipeline
An SCP or Config rule catches changes made by someone who bypassed the pipeline. This is covered in AWS Config conformance packs and in the landing-zone lesson.
AWS Console instructions
Most of this runs in CI, but the console is where you inspect the protection you configured:
- Console → CloudFormation → Stacks → your stack → Stack actions → Edit termination protection shows whether the stack is protected from deletion. Stack actions → Edit stack policy shows the policy that blocks replacement of named resources.
- Console → IAM → Roles, open the pipeline role. The Trust relationships tab shows who may assume it (the GitHub OIDC provider and conditions). Permissions shows its policies; look for wildcards. Permissions boundary shows the boundary if one is set.
- Console → IAM → Access Analyzer → Policy validation lets you paste a policy and see warnings before using it.
- Console → RDS → Databases → your DB → Configuration shows Deletion protection. Console → S3 → bucket → Properties shows versioning.
- Console → CloudFormation → Registry → Hooks lists activated Hooks ⚠ VERIFY the exact navigation in the current console.
AWS CLI
# --- cdk-nag runs inside `cdk synth`: any unacknowledged finding fails the command ---
cdk synth -c environmentName=dev
# --- CloudFormation Guard: validate a synthesised template against your rules (exit code 19 on failure) ---
cfn-guard validate --data cdk.out/hl-accounts-dev.template.json --rules rules/harbourline.guard --show-summary fail
# --- cfn-nag (Ruby gem): second opinion on the same template ---
cfn_nag_scan --input-path cdk.out/hl-accounts-dev.template.json
# --- Checkov on Terraform code, then on the plan ---
checkov -d infra/terraform --framework terraform --quiet --compact
terraform plan -out=tfplan
terraform show -json tfplan > tfplan.json
checkov -f tfplan.json --framework terraform_plan --quiet --compact
# --- The C# plan guard from this lesson (exit code 1 if a stateful resource is deleted or replaced) ---
dotnet run --project src/PlanGuard -- tfplan.json
# --- Stack protection (CloudFormation) ---
aws cloudformation update-termination-protection --enable-termination-protection \
--stack-name hl-accounts-prod --profile hl-prod
aws cloudformation set-stack-policy --stack-name hl-accounts-prod \
--stack-policy-body file://stack-policy.json --profile hl-prod
# --- Bootstrap a CDK environment with a customer-managed execution policy (not AdministratorAccess) ---
cdk bootstrap aws://333344445555/us-east-1 \
--cloudformation-execution-policies arn:aws:iam::333344445555:policy/hl-cfn-execution \
--trust 444455556666 --trust-for-lookup 444455556666 \
--custom-permissions-boundary hl-deploy-boundary \
--termination-protection true \
--profile hl-prodExit codes and flags differ between versions. Run each tool with --help once and ⚠ VERIFY the flags against the version you installed, especially cfn-guard validate summary options (-s all in older guides, --show-summary in newer ones).
Infrastructure as Code
cdk-nag v3 in a CDK (C#) app
cdk-nag v3 runs as a CDK policy-validation plugin, and acknowledgments use the CDK's own Validations API. The old suppression API from earlier versions is gone.
using Amazon.CDK;
using Cdklabs.CdkNag;
var app = new App();
// ... create your stacks here ...
// Register the AWS Solutions rule pack. Any finding that is not acknowledged fails `cdk synth`.
Validations.Of(app).AddPlugins(new AwsSolutionsChecks(app, new NagPackProps { Verbose = true }));
app.Synth();Rules for acknowledgments in a bank:
- One finding, one acknowledgment, one reason. Never acknowledge a whole rule "to make it pass".
- Reasons are reviewed like code. A reviewer should be able to say yes or no from the reason alone.
- Keep them next to the resource (in the stack that owns it) so that deleting the resource deletes the acknowledgment.
- Review them on a schedule. An acknowledgment is a risk acceptance, and risks expire.
- Know the pack's age. cdk-nag ships a PCI DSS pack for version 3.2.1 ⚠ VERIFY; that standard version has been retired in favour of v4.0.x, so treat the pack as a convenience, not a statement of PCI compliance.
CloudFormation Guard rule file
# Harbourline baseline rules for CloudFormation templates (and CDK output).
# Run: cfn-guard validate --data <template> --rules rules/harbourline.guard
let s3_buckets = Resources.*[ Type == 'AWS::S3::Bucket' ]
let databases = Resources.*[ Type == 'AWS::RDS::DBInstance' ]
rule s3_encrypted when %s3_buckets !empty {
%s3_buckets.Properties.BucketEncryption exists
<<
Violation: every S3 bucket must set BucketEncryption.
Fix: add ServerSideEncryptionConfiguration with SSE-KMS.
>>
}
rule s3_public_access_blocked when %s3_buckets !empty {
%s3_buckets.Properties.PublicAccessBlockConfiguration {
BlockPublicAcls == true
BlockPublicPolicy == true
IgnorePublicAcls == true
RestrictPublicBuckets == true
}
<<
Violation: all four public access block settings must be true.
>>
}
rule rds_protected when %databases !empty {
%databases.Properties.StorageEncrypted == true
%databases.Properties.DeletionProtection == true
%databases.Properties.PubliclyAccessible != true
%databases.DeletionPolicy in ['Retain', 'Snapshot']
<<
Violation: databases must be encrypted, deletion-protected, private, and kept (Retain or Snapshot) when the stack is deleted.
>>
}Guard syntax has evolved; ⚠ VERIFY the file against your installed version with cfn-guard validate, and use cfn-guard test to write unit tests for the rules themselves.
Checkov and cfn-nag
# Checkov on a Terraform folder. Skip a check only with a recorded reason.
checkov -d infra/terraform --framework terraform --quiet --compact --skip-check CKV_AWS_18
# A skip inside the code is better: it sits next to the resource and shows in the pull request
# resource "aws_s3_bucket" "audit" {
# #checkov:skip=CKV_AWS_18:Access logs go to the central log archive account via CloudTrail data events.
# bucket = var.bucket_name
# }
# Run Checkov from Docker with no local Python. Pin the tag in real pipelines. ⚠ VERIFY image name and tag
docker run --rm -v "${PWD}:/tf" bridgecrew/checkov -d /tf --quiet --compactResources:
AuditBucket:
Type: AWS::S3::Bucket
Metadata:
cfn_nag:
rules_to_suppress:
- id: W35
reason: "Access logging is provided by CloudTrail data events in the log archive account."Check IDs (for example CKV_AWS_18, W35) are examples for an S3 access-logging rule ⚠ VERIFY each ID against the tool's current documentation before you use it in a pipeline.
Protecting stateful resources
Resources:
AccountsDatabase:
Type: AWS::RDS::DBInstance
DeletionPolicy: Snapshot # stack delete takes a final snapshot
UpdateReplacePolicy: Snapshot # replacement during update keeps the old data as a snapshot
Properties:
DeletionProtection: true # service-level protection: the API refuses DeleteDBInstance
StorageEncrypted: true
# ... other properties{
"Statement": [
{ "Effect": "Allow", "Action": "Update:*", "Principal": "*", "Resource": "*" },
{
"Effect": "Deny",
"Action": ["Update:Replace", "Update:Delete"],
"Principal": "*",
"Resource": "LogicalResourceId/AccountsDatabase"
}
]
}In the CDK, the same intent is RemovalPolicy = RemovalPolicy.SNAPSHOT (databases) or RETAIN (buckets, keys), DeletionProtection = true on the database props, and TerminationProtection = true on the stack. cdk-nag rule AwsSolutions-RDS10 flags a database without deletion protection.
Least-privilege deploy roles
Trust: who can assume the apply role
The apply role is assumed only by a specific repository and environment through GitHub's OIDC provider. Replace the account and repository with your own.
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Principal": { "Federated": "arn:aws:iam::333344445555:oidc-provider/token.actions.githubusercontent.com" },
"Action": "sts:AssumeRoleWithWebIdentity",
"Condition": {
"StringEquals": {
"token.actions.githubusercontent.com:aud": "sts.amazonaws.com",
"token.actions.githubusercontent.com:sub": "repo:harbourline-example/platform-infra:environment:prod"
}
}
}
]
}The sub claim pins the role to one repository and one GitHub environment, and the prod environment has required reviewers, so a human approval stands between a commit and this role. ⚠ VERIFY the claim format and condition keys against the current GitHub and AWS documentation.
Permissions: plan role versus apply role
| Plan role | Apply role | |
|---|---|---|
| Used by | Pull request and plan jobs | The approved apply job only |
| AWS permissions | Read-only on the services in the stack (for example the AWS managed ReadOnlyAccess policy, narrowed if you can) | Create, update and delete only for the resource types in the stack, scoped by name prefix and tags where the service allows |
| State bucket | Read state; write and delete the lock file | Read and write state and the lock file |
| IAM | None | iam:CreateRole and iam:PutRolePolicy only with a permissions boundary condition; no iam:CreateUser, no iam:* on * |
| Can run on | Any pull request | A protected branch or tag, after approval |
The key IAM condition for roles the pipeline creates:
{
"Sid": "CreateRolesOnlyWithBoundary",
"Effect": "Allow",
"Action": ["iam:CreateRole", "iam:PutRolePolicy", "iam:AttachRolePolicy"],
"Resource": "arn:aws:iam::333344445555:role/hl-accounts-*",
"Condition": {
"StringEquals": {
"iam:PermissionsBoundary": "arn:aws:iam::333344445555:policy/hl-workload-boundary"
}
}
}With this, the pipeline cannot create a role more powerful than the boundary allows, even if the template asks for one.
CDK bootstrap: the five roles
Bootstrapping creates the roles the CDK uses: CloudFormationExecutionRole, DeploymentActionRole, FilePublishingRole, ImagePublishingRole and LookupRole. The execution role is what CloudFormation uses to create your resources, and by default it has AdministratorAccess. Replace it with a customer-managed policy using --cloudformation-execution-policies, add accounts to --trust and --trust-for-lookup only as needed, and enable --termination-protection for the bootstrap stack. Never delete a bootstrap stack that stacks depend on; there is no general recovery.
Complete code
The plan guard: a small C# tool plus tests. It reads the JSON from terraform show -json tfplan and fails the pipeline if a stateful resource would be deleted or replaced, unless a reviewer approved that exact address. Create this layout, or use the lab folder for the module project.
plan-guard/
PlanGuard.slnx
global.json (copy from backend/global.json)
src/PlanGuard/PlanGuard.csproj, PlanGuard.cs, Program.cs
tests/PlanGuard.Tests/PlanGuard.Tests.csproj, PlanGuardTests.cs<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net10.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
<RootNamespace>Harbourline.PolicyGuard</RootNamespace>
<InvariantGlobalization>true</InvariantGlobalization>
</PropertyGroup>
</Project>using System.Text.Json;
namespace Harbourline.PolicyGuard;
/// <summary>One stateful resource that the plan would delete or replace.</summary>
public sealed record PlanFinding(string Address, string Type, string Action, string Reason);
/// <summary>
/// Reads the JSON from `terraform show -json tfplan` and flags any plan that deletes or replaces a stateful resource.
/// Data stores are the one thing you cannot get back by re-running the pipeline.
/// </summary>
public static class PlanGuard
{
private static readonly HashSet<string> StatefulTypes = new(StringComparer.Ordinal)
{
"aws_db_instance",
"aws_rds_cluster",
"aws_dynamodb_table",
"aws_s3_bucket",
"aws_kms_key",
"aws_efs_file_system",
"aws_secretsmanager_secret",
"aws_ebs_volume",
};
/// <param name="planJson">Output of `terraform show -json plan.tfplan`.</param>
/// <param name="approvedAddresses">Resource addresses a human has explicitly approved for deletion or replacement.</param>
public static IReadOnlyList<PlanFinding> Check(string planJson, IReadOnlySet<string>? approvedAddresses = null)
{
approvedAddresses ??= new HashSet<string>();
var findings = new List<PlanFinding>();
using var document = JsonDocument.Parse(planJson);
if (!document.RootElement.TryGetProperty("resource_changes", out var changes))
{
return findings; // a plan with no changes has no resource_changes
}
foreach (var change in changes.EnumerateArray())
{
var type = change.GetProperty("type").GetString() ?? "";
var address = change.GetProperty("address").GetString() ?? "";
if (!StatefulTypes.Contains(type) || approvedAddresses.Contains(address))
{
continue;
}
var actions = change.GetProperty("change").GetProperty("actions")
.EnumerateArray()
.Select(a => a.GetString() ?? "")
.ToList();
if (!actions.Contains("delete"))
{
continue; // create, update and no-op are fine
}
// A replacement is reported as ["delete","create"] or ["create","delete"].
var action = actions.Contains("create") ? "replace" : "delete";
var reason = action == "replace"
? "The plan destroys and recreates this stateful resource. Data is lost unless it is restored."
: "The plan deletes this stateful resource.";
findings.Add(new PlanFinding(address, type, action, reason));
}
return findings;
}
}using Harbourline.PolicyGuard;
// Usage: plan-guard plan.json [--approve <resource address>]...
// Exit code 0 = safe to continue, 1 = stateful resources would be deleted or replaced, 2 = bad usage.
string? path = null;
var approved = new HashSet<string>(StringComparer.Ordinal);
for (var i = 0; i < args.Length; i++)
{
if (args[i] == "--approve" && i + 1 < args.Length)
{
approved.Add(args[++i]);
}
else
{
path = args[i];
}
}
if (path is null || !File.Exists(path))
{
Console.Error.WriteLine("Usage: plan-guard <plan.json> [--approve <address>]...");
return 2;
}
var findings = PlanGuard.Check(File.ReadAllText(path), approved);
if (findings.Count == 0)
{
Console.WriteLine("plan-guard: no stateful resource is deleted or replaced.");
return 0;
}
foreach (var f in findings)
{
Console.Error.WriteLine($"BLOCKED {f.Action,-8} {f.Address} ({f.Type}): {f.Reason}");
}
Console.Error.WriteLine($"plan-guard: {findings.Count} finding(s). Re-run with --approve <address> only after a reviewer has agreed.");
return 1;<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<OutputType>Exe</OutputType>
<IsPackable>false</IsPackable>
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="xunit.v3" Version="4.0.3" />
</ItemGroup>
<ItemGroup>
<Using Include="Xunit" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\src\PlanGuard\PlanGuard.csproj" />
</ItemGroup>
</Project>using Harbourline.PolicyGuard;
namespace Harbourline.PolicyGuard.Tests;
public class PlanGuardTests
{
private static string Plan(string type, string address, string actions) => $$"""
{ "resource_changes": [ { "address": "{{address}}", "type": "{{type}}", "change": { "actions": [{{actions}}] } } ] }
""";
[Fact]
public void Replacing_a_database_is_blocked()
{
var findings = PlanGuard.Check(Plan("aws_db_instance", "module.app.aws_db_instance.main", "\"delete\", \"create\""));
var f = Assert.Single(findings);
Assert.Equal("replace", f.Action);
Assert.Equal("module.app.aws_db_instance.main", f.Address);
}
[Fact]
public void Create_before_destroy_replacement_is_also_blocked()
{
var findings = PlanGuard.Check(Plan("aws_s3_bucket", "aws_s3_bucket.audit", "\"create\", \"delete\""));
Assert.Equal("replace", Assert.Single(findings).Action);
}
[Fact]
public void Deleting_a_kms_key_is_blocked()
{
var findings = PlanGuard.Check(Plan("aws_kms_key", "aws_kms_key.data", "\"delete\""));
Assert.Equal("delete", Assert.Single(findings).Action);
}
[Theory]
[InlineData("\"create\"")]
[InlineData("\"update\"")]
[InlineData("\"no-op\"")]
[InlineData("\"read\"")]
public void Non_destructive_actions_are_allowed(string actions)
{
Assert.Empty(PlanGuard.Check(Plan("aws_db_instance", "aws_db_instance.main", actions)));
}
[Fact]
public void Deleting_a_stateless_resource_is_allowed()
{
Assert.Empty(PlanGuard.Check(Plan("aws_security_group_rule", "aws_security_group_rule.old", "\"delete\"")));
}
[Fact]
public void A_reviewer_approved_address_is_skipped()
{
var approved = new HashSet<string> { "aws_s3_bucket.scratch" };
Assert.Empty(PlanGuard.Check(Plan("aws_s3_bucket", "aws_s3_bucket.scratch", "\"delete\""), approved));
}
[Fact]
public void A_plan_with_no_changes_is_fine()
{
Assert.Empty(PlanGuard.Check("""{ "format_version": "1.2" }"""));
}
}<Solution>
<Folder Name="/src/">
<Project Path="src/PlanGuard/PlanGuard.csproj" />
</Folder>
<Folder Name="/tests/">
<Project Path="tests/PlanGuard.Tests/PlanGuard.Tests.csproj" />
</Folder>
</Solution>Run the tests in Docker with your own NuGet cache volume (ten tests pass), then remove bin/ and obj/:
MSYS_NO_PATHCONV=1 docker run --rm --memory 3g \
-v "$PWD:/src" -v cea-nuget-m10:/root/.nuget/packages -w /src \
mcr.microsoft.com/dotnet/sdk:10.0 \
sh -c "dotnet test --solution PlanGuard.slnx; find . -type d \( -name bin -o -name obj \) -prune -exec rm -rf {} +"Wire it into the pipeline between plan and apply:
- run: terraform plan -out=tfplan
- run: terraform show -json tfplan > tfplan.json
- run: pip install checkov && checkov -f tfplan.json --framework terraform_plan --quiet --compact
- run: dotnet run --project src/PlanGuard -- tfplan.jsonCode explained line by line
StatefulTypeslists the resource types whose loss is expensive. Add your own (aws_sqs_queuewith unprocessed messages,aws_efs_file_system). The list is an explicit policy, not a guess.Checkopens the plan JSON withJsonDocument(no deserialisation classes needed) and readsresource_changes. A plan with no changes has noresource_changes, so the method returns an empty list.change.actionsis an array. A pure delete is["delete"]. A replacement is["delete","create"](destroy first) or["create","delete"](create_before_destroy). Both containdelete, so one check covers them.approvedAddresseslets a reviewer unblock one exact address. The guard never has a "skip everything" switch; approvals are per resource and visible in the pipeline definition.Program.csreturns exit code 1 for findings. Pipelines treat a non-zero exit as failure, so the apply job never starts.- The test helper builds plan JSON with a raw string literal (
$$"""), where doubled braces{{...}}are the interpolation holes and single braces are plain JSON. - Tests cover both replacement orders, a pure delete, non-destructive actions, a stateless delete, an approved address and a plan with no changes. Every guard-rail has a test proving it blocks, and one proving it does not over-block.
Security considerations
⚠ Learning shortcut — not for production
The lab runs every scan from your laptop and may use your SSO profile for plans. In production, scans run in CI under a read-only plan role, the apply role is assumed only by the approved pipeline job, and results are stored as build evidence. Never run Terraform or CDK against production with a personal administrator profile.
- The pipeline identity is a crown jewel. Anyone who controls a workflow file controls what the role can do. Protect workflow files with CODEOWNERS, require reviews, and restrict who can create tags or approve the
prodenvironment. - Scan third-party modules and providers. A registry module is code you did not write that runs with your credentials. Pin it and scan it.
- Plan files can contain secrets.
tfplanand the JSON export include resolved values. Store them as short-lived, access-controlled artefacts and delete them after use. - Fail closed. If the scanner crashes or cannot parse the plan, the job must fail, not pass. The C# guard throws on invalid JSON for this reason.
- Do not trust a green scan as proof of safety. Policy-as-code reduces a known class of mistakes. It is not a substitute for threat modelling, code review or your compliance team's judgement.
- Compliance note. These controls produce repeatable evidence for change management. They do not make you compliant with PCI DSS, UK GDPR or any other regime; your compliance team decides what is sufficient.
Banking use case
Harbourline's platform team runs the same checks on every infrastructure pull request. A pull request that renames a database identifier is flagged by the plan guard (BLOCKED replace module.accounts.aws_db_instance.main), so the author switches to a moved block and an in-place parameter change. A second pull request adds an S3 bucket without a public access block; Checkov fails it in under a minute with the ID and a fix hint. A third needs a security group open to a partner network; the engineer adds a Checkov skip with the partner's ticket number, and the reviewer approves because the reason names the ticket and the CIDR. Quarterly, the security team exports all skips and acknowledgments, closes those whose tickets are done and asks owners to renew the rest.
Common mistakes
- Scanning only code, never the plan. The code looks harmless; the plan shows
-/+. Scan both. - Skipping a whole check instead of a single resource.
--skip-checkfor the entire run hides new violations. Prefer inline skips with a reason. - Acknowledging with prefix IDs in cdk-nag v3. v3 matches finding IDs exactly, including the bracketed part (for example
AwsSolutions-IAM5[Resource::*]). A short ID silently does not match. AdministratorAccessas the deploy role. Quick to set up, impossible to defend. Start with a customer-managed policy and tighten from CloudTrail and Access Analyzer.- Relying on
prevent_destroyalone. It protects against one path (a Terraform plan). Add service deletion protection and a retain policy. - Letting scanners block forever on noise. Teams then disable them. Tune the rule set, own it, and measure false positives.
- Treating suppression as one-way. An acknowledgment with no owner or review date never gets revisited.
Troubleshooting
| Symptom | Likely cause | Fix |
|---|---|---|
cdk synth fails with AwsSolutions-... findings | Unacknowledged cdk-nag findings | Fix the resource, or acknowledge the exact finding ID with a reason |
| Acknowledgment has no effect in cdk-nag v3 | ID is a prefix; v3 matches exactly, including [...] | Copy the full ID from the finding output |
cfn-guard validate exits with code 19 | One or more rules failed (that is the intended signal) | Read the summary; fix the template or the rule |
cfn-guard reports a rule syntax error | Guard version differs from the guide you followed | Run cfn-guard --version; adjust syntax; use cfn-guard test |
| Checkov flags something already suppressed in code | Skip comment is outside the resource block, or the check ID is wrong | Put #checkov:skip=ID:reason inside the block; confirm the ID in the output |
terraform show -json prints nothing useful | Plan file missing or from a different working directory | Re-run terraform plan -out=tfplan in the same folder, then show -json tfplan |
| Plan guard blocks a harmless replacement of a scratch bucket | The type is on the stateful list | Pass --approve <address> after review, or remove the type from the list for that environment |
AccessDenied from the plan role during plan | The role is missing a read permission for a service in the stack | Add the specific read action; do not widen to * |
Not authorized to perform sts:AssumeRoleWithWebIdentity | Trust policy sub does not match the repo or environment | Fix the sub condition and make the job use the named GitHub environment |
Cost and cleanup
Everything in the main exercise runs locally or in CI and costs nothing: tests, Checkov, cfn-guard, cfn-nag and the plan guard have no AWS charges. If you create the optional IAM roles and the bootstrap stack in the sandbox account, IAM roles are free; the bootstrap stack creates an S3 bucket and an ECR repository that cost pennies while empty. ⚠ VERIFY current ECR and S3 prices if you keep them.
# Optional: remove what the exercise created (replace names and account IDs)
aws iam delete-role-policy --role-name hl-lab-plan-role --policy-name state-access --profile learn-sandbox
aws iam detach-role-policy --role-name hl-lab-plan-role --policy-arn arn:aws:iam::aws:policy/ReadOnlyAccess --profile learn-sandbox
aws iam delete-role --role-name hl-lab-plan-role --profile learn-sandbox
# If you bootstrapped a throwaway environment, empty the assets bucket and delete the CDKToolkit stack
# (never do this in an account where other CDK stacks still exist).
aws cloudformation delete-stack --stack-name CDKToolkit --profile learn-sandbox
aws resourcegroupstaggingapi get-resources \
--tag-filters Key=Lab,Values=m10-l13 \
--profile learn-sandbox --region us-east-1 \
--query "ResourceTagMappingList[].ResourceARN"Exercises
- 🟢 Guided: build the
plan-guardfolder, run the ten tests, then create a tiny Terraform configuration with oneaws_s3_bucket, plan it, changebucketto a new name and runterraform plan -out=tfplanthenterraform show -json tfplan > tfplan.json. Run the guard and confirm it blocks the replacement. - 🟡 Challenge: extend the guard with a second check: fail the plan if any
aws_security_group_ruleoraws_vpc_security_group_ingress_ruleis created or updated with a CIDR of0.0.0.0/0for port 22 or 3389. Write four tests (blocked and allowed variants for each port) before writing the code. - 🔴 Live problem: your CISO asks, "Prove to me that nobody can drop the production accounts database through the pipeline, through Terraform on a laptop, or through the console." List every layer you would put in place (stack and Terraform settings, deletion protection, roles and boundaries, SCP, alarms on
DeleteDBInstancein CloudTrail), state which path each layer covers, and which paths remain open and who owns that residual risk.
Assignment
Create a policy-as-code folder in your portfolio repository containing: the plan-guard project with tests; a rules/harbourline.guard file with at least three rules and Guard unit tests; a .github/workflows plan job that runs Checkov and the guard; and a one-page SECURITY-DEPLOY.md describing the plan role, the apply role, the trust condition and the protected resources. Include a table of every suppression or acknowledgment with its reason and an owner.
Solutions
Changing the bucket name of an existing aws_s3_bucket forces replacement, so the plan shows -/+ and resource_changes[].change.actions is ["delete","create"]. The guard prints BLOCKED replace aws_s3_bucket.<name> (aws_s3_bucket): ... and exits with code 1. Re-run with --approve aws_s3_bucket.<name> to see it exit 0, which demonstrates the approval path. Note that approving does not make the replacement safe: it only records that a human decided to accept it.
For the extra check, iterate resource_changes, keep types aws_security_group_rule and aws_vpc_security_group_ingress_rule, skip changes whose actions contain only delete or no-op, and read change.after (an object). For aws_vpc_security_group_ingress_rule the attributes are cidr_ipv4, from_port and to_port; for aws_security_group_rule they are cidr_blocks (an array), from_port, to_port and type. Flag when the CIDR is 0.0.0.0/0 and the port range includes 22 or 3389 (from_port <= port && port <= to_port). Write the tests first: ingress open to the world on 22 (blocked), on 3389 (blocked), on 443 (allowed), and a narrow CIDR on 22 (allowed). Handle values that are unknown at plan time (they appear in after_unknown); treat an unknown CIDR as a finding that needs review, so the guard fails closed.
For the live problem, a strong answer lists: DeletionPolicy/UpdateReplacePolicy Snapshot and termination protection (stack deletes), deletion_protection on the instance (any API caller, including the console and CLI), prevent_destroy plus the plan guard (Terraform plans), a stack policy denying Update:Replace and Update:Delete (CloudFormation updates), an apply role without rds:DeleteDBInstance and a human-only break-glass role for it, an SCP denying rds:DeleteDBInstance for non-break-glass roles in the production OU, and a CloudTrail-based alarm on any DeleteDBInstance or ModifyDBInstance that disables protection. Residual risk: a break-glass administrator can still remove protection deliberately; that is governed by access approvals and monitoring, owned by security operations.
Knowledge check
Answer: the code does not tell you whether a change updates a resource in place or destroys and recreates it. The plan does. Destructive changes to stateful resources can only be caught reliably at plan time.
Answer: with Validations.Of(scope).Acknowledge(...), passing an Acknowledgment with the exact finding ID (including the bracketed part when present) and a reason. The older suppression API was removed.
Answer: DeletionPolicy applies when the resource or stack is deleted; Snapshot takes a snapshot first. UpdateReplacePolicy applies when an update replaces the resource, so the old one is snapshotted or retained rather than silently lost.
Answer: by default the bootstrap grants the execution role administrator permissions, and any account in the trust list can use them through the deploy role. Supply a customer-managed policy with --cloudformation-execution-policies, limit --trust and add a permissions boundary.
Answer: no. It only makes Terraform plans that would destroy the resource fail. Use service deletion protection, restricted IAM and SCPs for other paths.
Interview questions
- How do you stop an infrastructure change from deleting a production database? Layers: deletion protection on the database, retain or snapshot policies,
prevent_destroyor a stack policy, a plan-time check that fails on delete or replace of stateful resource types, a pipeline role without delete permission for that resource, and an SCP for anyone bypassing the pipeline. - How do you choose between cdk-nag, Checkov and cfn-guard? Use the tool native to your authoring language for fast feedback (cdk-nag for CDK, Checkov for Terraform), and cfn-guard for the bank's own rules where you want one engine across templates and plan JSON. Avoid running every tool on everything; duplicate findings erode trust.
- What goes wrong with suppressions? They become permanent and unowned. Require a reason, an owner and a review date, keep them beside the resource and review the full list on a schedule.
- How should a pipeline authenticate to AWS? With OIDC federation to a role scoped to one repository and environment, issuing short-lived credentials, with no stored access keys and a separate read-only role for plans.
Certification practice
A company deploys infrastructure with Terraform from a CI/CD pipeline. After an incident in which a plan replaced a production database, management wants an automated control that blocks any plan that deletes or replaces data stores unless a reviewer approves it. Which solution is MOST appropriate?
A. Run terraform fmt before every apply.
B. Export the plan as JSON and add a pipeline step that fails when a stateful resource has a delete action, with an explicit per-resource approval list.
C. Add a README warning to the repository.
D. Give the pipeline role AdministratorAccess so it can recover quickly.
Answer: B. The plan JSON lists each resource's actions, so a step can block deletes and replacements before apply, and approvals remain per resource. A only formats code. C is not a control. D widens the blast radius.
An organisation wants developers to deploy with CDK into workload accounts but must ensure that any IAM role created by a deployment cannot exceed an approved maximum set of permissions, even if a template requests more. What should the architect implement?
A. Require every developer to have AdministratorAccess in workload accounts.
B. Configure the CDK bootstrap execution policy and apply a permissions boundary that the deployment role requires on any role it creates (using the iam:PermissionsBoundary condition), with SCPs as a backstop.
C. Disable CloudTrail in workload accounts.
D. Ask developers to review IAM policies by eye.
Answer: B. A permissions boundary caps the effective permissions of roles created by deployments, and the condition prevents creating roles without it. SCPs add an organisation-level guard. A, C and D remove or ignore controls.
Completion checklist
- I can name the four moments to check and what each catches
- I ran the ten plan-guard tests and saw a replacement blocked
- I can acknowledge a cdk-nag v3 finding with an exact ID and a reason
- I can describe the plan role, the apply role and the OIDC trust condition
- I can list four layers that protect a production database from deletion
- I ran the cleanup steps and confirmed nothing is still billing
Key takeaways
- Check at several moments: code, template, plan, and in the account. The plan is the only place that shows replace versus update.
- cdk-nag v3 uses the CDK Validations API; acknowledge exact finding IDs with reasons.
- Give pipelines a read-only plan role and a narrow, boundary-limited apply role, assumed by OIDC; replace the default administrator execution policy.
- Protect stateful resources in layers: retain or snapshot policies, deletion protection,
prevent_destroy, stack policies and a plan guard. - Suppressions are risk acceptances. Record owners and review them.
Further reading
- AWS CDK bootstrapping
- cdk bootstrap command reference
- cdk-nag on GitHub
- AWS CloudFormation Guard: validate command
- Checkov: suppressing and skipping policies
- Terraform: the lifecycle meta-argument
- AWS Control Tower: how controls work
- Previous: Environment configuration and versioning · Next: Landing-zone automation 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.
Environment configuration and versioning
Promote the same infrastructure code through dev, test and prod by changing only reviewed configuration, guard production settings with an xUnit test, and tag releases so you can always answer which version is running where.
Landing-zone automation overview
Understand what AWS Control Tower, Account Factory, Account Factory for Terraform and Customizations for Control Tower each automate, design a Harbourline landing zone on paper, and validate account requests with a tested C# check before anything is provisioned.