Skip to Content
Cloud Engineering Academy
10. Infrastructure as Code

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.

advanced⏱ 2 h 30 min🟢 FreeDOP-C02SOA-C03SAP-C03

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_destroy and 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

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:

  1. While you type. Editor plugins and pre-commit hooks. Fast, advisory.
  2. In the pull request. The scanner reads the code or the synthesised template. Blocks the merge.
  3. On the plan. The scanner reads what is about to change, including deletes and replacements. Blocks the apply.
  4. 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

ToolInputLanguageBest atWatch out for
cdk-nagCDK construct tree during synthRule packs in code; acknowledgments in C#Fast feedback in a CDK app; rule packs such as AWS SolutionsOnly checks CDK apps; findings can be noisy on helper constructs
CloudFormation Guard (cfn-guard)Any JSON or YAML (templates, Terraform plan JSON)Guard DSLCustom bank rules you own; also usable as a CloudFormation Hook ⚠ VERIFYYou write and maintain the rules
cfn-nagCloudFormation templates (including CDK output)Ruby rule set, Metadata for suppressionsQuick lint of templates for common security smellsSmaller rule set; confirm the project is still actively maintained ⚠ VERIFY
CheckovTerraform code, Terraform plan JSON, CloudFormation, and morePython, many built-in checks, custom checksBroad coverage with a large built-in policy libraryMany checks flag "best practice" items; tune and record skips
Plan guard (this lesson)terraform show -json planYour own C#Blocking destructive changes to stateful resourcesOnly knows what you teach it
SCPs, Config rules, Control Tower controlsLive AWS accountJSON / managed rulesSafety net even if the pipeline is bypassedDetects 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 equivalentWhat'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 templatescdk-nag, cfn-guard, Checkov on the template or plan before deployYou run these in CI; AWS does not do it for you
Microsoft Defender for DevOps / IaC scanningCheckov, cfn-nag, cdk-nag, plus Amazon Inspector for what is already runningMostly open-source tools you add to the pipeline
Service principal for deployments, with a custom roleA pipeline IAM role assumed by OIDC, with a narrow policy and a permissions boundaryShort-lived credentials via role assumption; no stored secret
Resource locks (CanNotDelete)DeletionPolicy: Retain, termination protection, stack policies, prevent_destroy, service deletion protectionSeveral 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:

  1. 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.
  2. 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.
  3. Console → IAM → Access Analyzer → Policy validation lets you paste a policy and see warnings before using it.
  4. Console → RDS → Databases → your DB → Configuration shows Deletion protection. Console → S3 → bucket → Properties shows versioning.
  5. 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-prod

Exit 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

rules/harbourline.guard
# 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 --compact
template.yaml (cfn-nag suppression example)
Resources:
  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

Retain policies, stack policy and termination protection
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
stack-policy.json
{
  "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.

apply-role-trust.json
{
  "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 roleApply role
Used byPull request and plan jobsThe approved apply job only
AWS permissionsRead-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 bucketRead state; write and delete the lock fileRead and write state and the lock file
IAMNoneiam:CreateRole and iam:PutRolePolicy only with a permissions boundary condition; no iam:CreateUser, no iam:* on *
Can run onAny pull requestA protected branch or tag, after approval

The key IAM condition for roles the pipeline creates:

apply-role-iam-guard.json (excerpt)
{
  "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
src/PlanGuard/PlanGuard.csproj
<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>
src/PlanGuard/PlanGuard.cs
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;
    }
}
src/PlanGuard/Program.cs
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;
tests/PlanGuard.Tests/PlanGuard.Tests.csproj
<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>
tests/PlanGuard.Tests/PlanGuardTests.cs
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" }"""));
    }
}
PlanGuard.slnx
<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:

.github/workflows/terraform-plan.yml (excerpt)
      - 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.json

Code explained line by line

  1. StatefulTypes lists the resource types whose loss is expensive. Add your own (aws_sqs_queue with unprocessed messages, aws_efs_file_system). The list is an explicit policy, not a guess.
  2. Check opens the plan JSON with JsonDocument (no deserialisation classes needed) and reads resource_changes. A plan with no changes has no resource_changes, so the method returns an empty list.
  3. change.actions is an array. A pure delete is ["delete"]. A replacement is ["delete","create"] (destroy first) or ["create","delete"] (create_before_destroy). Both contain delete, so one check covers them.
  4. approvedAddresses lets a reviewer unblock one exact address. The guard never has a "skip everything" switch; approvals are per resource and visible in the pipeline definition.
  5. Program.cs returns exit code 1 for findings. Pipelines treat a non-zero exit as failure, so the apply job never starts.
  6. The test helper builds plan JSON with a raw string literal ($$"""), where doubled braces {{...}} are the interpolation holes and single braces are plain JSON.
  7. 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 prod environment.
  • 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. tfplan and 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-check for 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.
  • AdministratorAccess as 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_destroy alone. 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

SymptomLikely causeFix
cdk synth fails with AwsSolutions-... findingsUnacknowledged cdk-nag findingsFix the resource, or acknowledge the exact finding ID with a reason
Acknowledgment has no effect in cdk-nag v3ID is a prefix; v3 matches exactly, including [...]Copy the full ID from the finding output
cfn-guard validate exits with code 19One or more rules failed (that is the intended signal)Read the summary; fix the template or the rule
cfn-guard reports a rule syntax errorGuard version differs from the guide you followedRun cfn-guard --version; adjust syntax; use cfn-guard test
Checkov flags something already suppressed in codeSkip comment is outside the resource block, or the check ID is wrongPut #checkov:skip=ID:reason inside the block; confirm the ID in the output
terraform show -json prints nothing usefulPlan file missing or from a different working directoryRe-run terraform plan -out=tfplan in the same folder, then show -json tfplan
Plan guard blocks a harmless replacement of a scratch bucketThe type is on the stateful listPass --approve <address> after review, or remove the type from the list for that environment
AccessDenied from the plan role during planThe role is missing a read permission for a service in the stackAdd the specific read action; do not widen to *
Not authorized to perform sts:AssumeRoleWithWebIdentityTrust policy sub does not match the repo or environmentFix 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-guard folder, run the ten tests, then create a tiny Terraform configuration with one aws_s3_bucket, plan it, change bucket to a new name and run terraform plan -out=tfplan then terraform 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_rule or aws_vpc_security_group_ingress_rule is created or updated with a CIDR of 0.0.0.0/0 for 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 DeleteDBInstance in 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

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

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_destroy or 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

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

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.

On this page