โšก
Zero to Platform Architect2026
Phase 2: IaC & Policy-as-Code

Lesson 2: Policy-as-Code (Checkov & Open Policy Agent)

๐Ÿง  The Concept (Explain Like Iโ€™m 5)

Imagine airport security:

  • The Bad Approach (Reactive Security): Airport guards let anyone board the airplane without checking bags. Once the plane is at 35,000 feet, guards start searching suitcases. If someone brought a dangerous item, everyone is already in danger (This is monitoring cloud misconfigurations directly in production).
  • The Good Approach (Shift-Left Security): Before anyone even steps into the terminal, their bags pass through high-speed X-ray scanners and metal detectors. If prohibited items are detected, the passenger is halted at the gate (This is Policy-as-Code running in your Git Pull Requests).

Policy-as-Code means writing security, compliance, and governance rules as machine-executable code:

  • If an engineer writes Terraform that opens an S3 bucket to the public, creates an unencrypted database, or allows SSH (port 22) from 0.0.0.0/0, the automated CI pipeline halts execution and blocks the PR immediately.
  • Not a single byte of cloud infrastructure is ever provisioned until the code passes every security check.

๐Ÿข The Enterprise Context (Why Platform Architects Care)

  1. The Cloud Security Posture Reality: According to industry incident response reports, over 80% of enterprise cloud data breaches originate not from zero-day kernel exploits, but from basic cloud misconfigurations (unencrypted EBS volumes, public S3 buckets, overly permissive security groups, missing MFA).
  2. Review Scalability Bottleneck: In an organization with 300 software engineers and 5 platform security engineers, hundreds of Pull Requests are submitted every week. Humans cannot manually inspect every line of HCL for compliance. Automated policy gates act as tire spikes that catch mistakes before code merges.
  3. Regulatory Compliance (SOC2, HIPAA, PCI-DSS, ISO 27001): Regulators require proof that continuous compliance is enforced systematically. Policy-as-Code provides an immutable, version-controlled audit trail proving that unencrypted databases or non-compliant infrastructure cannot physically be deployed.

๐Ÿ—บ๏ธ Visual Architecture: The Shift-Left Security Pipeline

flowchart TD
    Dev["๐Ÿ‘จโ€๐Ÿ’ป Engineer<br/>(Submits Pull Request)"] --> GitHub["GitHub Actions CI Pipeline"]

    subgraph StaticGates ["Phase 1: Static AST Code Analysis"]
        Fmt["terraform fmt -check"] --> Val["terraform validate"]
        Val --> Checkov{"<b>Checkov Static Engine</b><br/>(Scans HCL AST against 1,000+ CIS Benchmarks)"}
    end

    subgraph DynamicGates ["Phase 2: Plan-Time Policy Evaluation"]
        TFPlan["terraform plan -out=tfplan.binary"] --> TFShow["terraform show -json > tfplan.json"]
        TFShow --> OPA{"<b>OPA Rego Engine</b><br/>(Evaluates custom org rules against planned state)"}
    end

    GitHub --> StaticGates
    Checkov -->|"Fail: High/Critical CVE"| BlockPR["โŒ Block PR Merge & Post Inline Review Comment"]
    Checkov -->|"Pass Static Checks"| DynamicGates
    OPA -->|"Fail: Rule Violation"| BlockPR
    
    OPA -->|"Pass All Governance Gates"| Infracost["Infracost (Budget & Cloud Spend Check)"]
    Infracost --> Review["Peer Senior Review & Approval"]
    Review --> Apply["terraform apply (Production Cloud)"]

๐Ÿ”ฌ Under the Hood: Static AST Analysis vs. Plan-Time Evaluation

Understanding the technical difference between static code scanning and plan-time evaluation is essential:

Dimension Static AST Scanning (Checkov / tfsec) Plan-Time Evaluation (OPA / Sentinel)
Input Analyzed Raw .tf source code files tfplan.json compiled execution plan
How It Parses Builds an Abstract Syntax Tree (AST) of HCL Analyzes resolved JSON state produced by Terraform engine
Variables & Locals Evaluates only hardcoded values or default variables Fully resolves all dynamic variables, locals, and formulas
External Data Cannot read data sources (data.aws_ami, SSM) Includes outputs fetched from live cloud APIs
Speed Instantaneous (< 2 seconds) Requires running terraform plan first (~30โ€“90 seconds)
Best Used For Catching obvious misconfigurations early (missing encryption) Complex enterprise logic (e.g. cross-resource CIDR checks)

๐Ÿ“œ Open Policy Agent (OPA) & Rego Deep Dive

Open Policy Agent (OPA) is an open-source, general-purpose policy engine hosted by the CNCF. It uses a declarative query language called Rego (inspired by Datalog).

How Rego Evaluates Code

  • In traditional programming (Python, Go), you write imperative loops: if resource == x and port == y: return false.
  • In Rego, you declare assertions. You describe the set of conditions that constitute a violation. If an object matches all assertions, it is added to a deny set.

[!IMPORTANT] Language Clarity: Why OPA Uses Rego (Not Python) Engineers often ask: โ€œCan I write OPA policies in Python?โ€
No. OPA policies are written exclusively in Rego because Rego is designed for deterministic, side-effect-free mathematical assertions with sub-millisecond evaluation speed.
However, in production platforms, Python acts as the outer orchestrator and test harness around OPAโ€”parsing tfplan.json, querying OPAโ€™s HTTP Decision API, and executing serverless auto-remediation via AWS Lambda! (See Lesson 7: Python for Platform Engineers & AWS Lambda for the complete implementation).

flowchart LR
    Input["Input JSON<br/>(tfplan.json)"] --> OPADaemon["OPA Decision Engine"]
    Data["Policy Rules<br/>(rules.rego)"] --> OPADaemon
    OPADaemon --> Decision["Decision Output<br/>{ 'deny': ['Bucket must be encrypted!'] }"]

Production Rego Policy (policies/enterprise_guardrails.rego)

This production policy enforces two critical enterprise mandates:

  1. All S3 buckets must have Server-Side Encryption (SSE) enabled.
  2. No Security Group may allow inbound SSH (port 22) from 0.0.0.0/0.
package terraform.security

import future.keywords.in

default allow = false

# ==============================================================================
# Rule 1: Deny Unencrypted S3 Buckets
# ==============================================================================
deny[msg] {
    # Iterate through all resource changes in the planned terraform state
    resource := input.resource_changes[_]
    resource.type == "aws_s3_bucket"
    
    # Check if resource is being created or updated
    actions := resource.change.actions
    count([a | a := actions[_]; a in ["create", "update"]]) > 0

    # Ensure a server-side encryption configuration block is declared
    not has_s3_encryption(resource.address)

    msg := sprintf("SECURITY VIOLATION: S3 Bucket '%v' must have server-side encryption configured via 'aws_s3_bucket_server_side_encryption_configuration'!", [resource.address])
}

# Helper rule to verify companion encryption resource exists in plan
has_s3_encryption(bucket_address) {
    encryption_resource := input.resource_changes[_]
    encryption_resource.type == "aws_s3_bucket_server_side_encryption_configuration"
    encryption_resource.change.after.bucket == bucket_address
}

# ==============================================================================
# Rule 2: Deny Ingress Port 22 (SSH) from 0.0.0.0/0
# ==============================================================================
deny[msg] {
    resource := input.resource_changes[_]
    resource.type == "aws_security_group_rule"
    resource.change.after.type == "ingress"
    
    # Check if rule allows all IPs
    cidr := resource.change.after.cidr_blocks[_]
    cidr == "0.0.0.0/0"
    
    # Check if port range includes port 22
    from_port := resource.change.after.from_port
    to_port := resource.change.after.to_port
    is_port_22(from_port, to_port)

    msg := sprintf("CRITICAL BREACH: Security Group Rule '%v' exposes SSH (Port 22) directly to the public internet (0.0.0.0/0)!", [resource.address])
}

is_port_22(from, to) {
    from <= 22
    to >= 22
}

Native Unit Testing for Rego (policies/enterprise_guardrails_test.rego)

Enterprise policy must be tested just like production application code:

package terraform.security_test

import data.terraform.security

# Test Case 1: Deny rule triggers when Security Group opens port 22 to the world
test_deny_open_ssh {
    mock_input := {
        "resource_changes": [
            {
                "address": "aws_security_group_rule.bad_ssh",
                "type": "aws_security_group_rule",
                "change": {
                    "actions": ["create"],
                    "after": {
                        "type": "ingress",
                        "from_port": 22,
                        "to_port": 22,
                        "cidr_blocks": ["0.0.0.0/0"]
                    }
                }
            }
        ]
    }
    violations := security.deny with input as mock_input
    count(violations) == 1
}

# Test Case 2: Allow rule passes when Security Group restricts SSH to corporate VPN CIDR
test_allow_restricted_ssh {
    mock_input := {
        "resource_changes": [
            {
                "address": "aws_security_group_rule.safe_ssh",
                "type": "aws_security_group_rule",
                "change": {
                    "actions": ["create"],
                    "after": {
                        "type": "ingress",
                        "from_port": 22,
                        "to_port": 22,
                        "cidr_blocks": ["10.50.0.0/16"] # Internal Corporate VPN only
                    }
                }
            }
        ]
    }
    violations := security.deny with input as mock_input
    count(violations) == 0
}

๐Ÿค– Production GitHub Actions Policy Enforcement Workflow

This automated workflow executes Checkov and OPA on every Pull Request, formats violations into markdown, and blocks the merge button if critical issues exist:

# .github/workflows/policy-enforcement.yml
name: Policy-as-Code Gatekeeper

on:
  pull_request:
    branches: [main]

jobs:
  compliance-gate:
    runs-on: ubuntu-latest
    permissions:
      contents: read
      pull-requests: write

    steps:
      - name: Checkout Repository
        uses: actions/checkout@v4

      - name: Setup Terraform
        uses: hashicorp/setup-terraform@v3
        with:
          terraform_version: 1.8.2

      - name: Setup OPA
        uses: open-policy-agent/setup-opa@v2
        with:
          version: 0.64.0

      - name: Run Checkov Static Analysis
        name: checkov
        id: checkov
        uses: bridgecrewio/checkov-action@master
        with:
          framework: terraform
          output_format: cli,json
          output_file_path: checkov_report.txt,checkov_report.json
          soft_fail: false # Hard-fail on policy violations!

      - name: Terraform Init & Plan
        id: plan
        run: |
          terraform init
          terraform plan -out=tfplan.binary
          terraform show -json tfplan.binary > tfplan.json

      - name: Run OPA Policy Unit Tests
        run: opa test policies/ -v

      - name: Evaluate OPA Compliance Policies
        id: opa_eval
        run: |
          VIOLATIONS=$(opa eval --data policies/ --input tfplan.json "data.terraform.security.deny" --format raw)
          echo "violations=${VIOLATIONS}" >> $GITHUB_OUTPUT
          if [ "${VIOLATIONS}" != "[]" ] && [ "${VIOLATIONS}" != "set()" ]; then
            echo "โŒ Policy violations detected: ${VIOLATIONS}"
            exit 1
          fi

      - name: Post PR Review Comment on Failure
        if: failure()
        uses: actions/github-script@v7
        with:
          script: |
            github.rest.issues.createComment({
              issue_number: context.issue.number,
              owner: context.repo.owner,
              repo: context.repo.repo,
              body: `### โŒ Shift-Left Security Pipeline Failed!
              Your Pull Request violates enterprise security policies.
              Please review the Checkov and OPA rule outputs in the workflow logs before requesting re-review.`
            })

๐Ÿ› ๏ธ Step-by-Step Command Playbook

# 1. Run Checkov locally against current Terraform workspace
checkov -d . --framework terraform --compact

# 2. Run Checkov filtering for HIGH and CRITICAL severity only
checkov -d . --framework terraform --check CKV_AWS_* --hard-fail-on HIGH,CRITICAL

# 3. Create a Checkov baseline file (Records legacy violations so they don't block new PRs)
checkov -d . --create-baseline --output-file-path .checkov.baseline

# 4. Generate JSON execution plan for OPA evaluation
terraform plan -out=tfplan.binary
terraform show -json tfplan.binary > tfplan.json

# 5. Execute OPA policy evaluation against the JSON plan
opa eval --data policies/ --input tfplan.json "data.terraform.security.deny"

# 6. Execute OPA policy unit tests
opa test policies/ -v

โš ๏ธ Real-World Failure Modes & Troubleshooting Playbook

Scenario 1: The โ€œUndefined vs Falseโ€ Rego Trap

  • Symptom: You write a rule expecting it to allow compliant resources, but OPA outputs undefined instead of false, causing your CI pipeline to crash or behave unpredictably.
  • Root Cause: In Rego, if an expression references a field that does not exist in the JSON document (e.g., input.resource_changes[_].change.after.logging[0].enabled), the entire rule evaluates to undefined rather than boolean false.
  • Resolution: Always use the default keyword and verify attribute existence using helper rules or the in keyword:
    # Declare explicit default fallback value
    default allow = false
    
    # Protect against null or missing attributes
    has_logging(change) {
        change.after.logging != null
        count(change.after.logging) > 0
    }

Scenario 2: Inline Policy Suppressions & Auditing

  • Symptom: An enterprise has a legitimate business need to allow public ingress (e.g., an internet-facing Application Load Balancer needs port 443 open to 0.0.0.0/0), but the automated Checkov pipeline blocks the PR.
  • Resolution: Never disable the security gate globally. Implement an in-code auditable suppression annotated with the security ticket ID:
    # bridgecrew:skip=CKV_AWS_260: "Public Internet ALB requires ingress on 443 by architecture design. Approved in SEC-7819"
    resource "aws_security_group_rule" "public_https" {
      type        = "ingress"
      from_port   = 443
      to_port     = 443
      protocol    = "tcp"
      cidr_blocks = ["0.0.0.0/0"]
      security_group_id = aws_security_group.alb.id
    }

๐Ÿ“ Staff Architect & SRE Interview Scenarios

โ“ Question 1: The Phased Enterprise Policy Rollout Strategy

Question: If an organization with 1,500 active Terraform repositories hires you to implement Policy-as-Code, why should you NEVER enable hard blocking gates on Day 1, and what rollout framework should you execute?

Answer: Enabling hard-blocking gates on Day 1 will immediately fail hundreds of existing repositories containing legacy technical debt, paralyzing developer velocity and causing severe organizational pushback. A mature platform architect implements a three-phase rollout strategy:

  1. Phase 1: Visibility & Baseline (Month 1): Deploy Checkov in CI with --soft-fail. Record all pre-existing violations into .checkov.baseline. Violations post informational comments on PRs without blocking merges.
  2. Phase 2: Enforce on Net-New Code (Month 2): Configure the pipeline to hard-fail only on new violations introduced by the current PR while ignoring baselined legacy debt.
  3. Phase 3: Remediation & Ratcheting (Month 3+): Dedicate platform sprint cycles to remediate baselined issues by module priority, ratcheting down the baseline until 100% compliance is reached.
โ“ Question 2: Static Analysis (Checkov) vs Cloud Control Plane Policies (AWS SCP / Azure Policy)

Question: If AWS Service Control Policies (SCPs) and Azure Policy already exist to prevent non-compliant resource creation at the cloud API layer, why does an enterprise still need Shift-Left tools like Checkov and OPA in Git?

Answer: SCPs and Azure Policies operate at the cloud control plane (runtime). When an SCP blocks a RunInstances or CreateBucket API call, Terraform fails halfway through an apply, leaving state partially applied, half-provisioned resources hanging, and CI pipelines locked. The developer receives a cryptic AWS API authorization error after waiting 10 minutes for an apply.

Defense-in-Depth: Shift-Left tools catch violations in under 5 seconds during the Git Pull Request phase, providing immediate, clear remediation instructions before any cloud resources are touched. SCPs remain the unbreakable guardrail of last resort, while Policy-as-Code provides developer velocity and prevention.