5 min read

Security and Governance in Infrastructure - Policy as Code with OPA

1. The Problem: Errors That Only Show Up After Apply

In the previous article of this series, we saw how to keep secrets from leaking in plain text. But there’s an equally common and subtler category of error: a technically correct terraform apply — no syntax error, no exposed secret — that still creates an insecure resource: a public S3 bucket, a security group opening 0.0.0.0/0 on port 22, an unencrypted disk. None of this breaks the plan. Only an attentive human reviewer (or an incident) finds out afterwards.

Manual code review doesn’t scale and is fallible — nobody reads 40 .tf files in a big PR line by line looking for a wrong cidr_blocks. This is exactly the problem Policy as Code solves: turning security rules into executable code that runs automatically before apply and blocks whatever violates the policy — without relying on someone remembering to look.

2. What Policy as Code Is

Policy as Code is the practice of writing governance rules (security, compliance, naming conventions, mandatory tags) as versioned, testable code that runs automatically at some point in the pipeline — usually between plan and apply. The two most widely used tools in the IaC ecosystem are:

  • OPA (Open Policy Agent), an open source, tool-agnostic policy engine maintained by the CNCF, with its own rule language called Rego.
  • Sentinel, HashiCorp’s proprietary solution, available in Terraform Cloud/Enterprise, with native integration into the Terraform plan.

We’ll focus on OPA because it’s open source, free and usable in any pipeline (GitHub Actions, GitLab CI, Jenkins), whether or not you’re on Terraform Cloud.

3. Rego: OPA’s Policy Language

Rego is a declarative language focused on asking questions about structured data (typically JSON). A Rego policy doesn’t “execute steps” — it declares conditions that, if true, produce a violation (deny) or a decision (allow). The basic block:

package terraform.security

deny[msg] {
    # condition that, if true, produces a violation message
    msg := "example violation"
}

The most common pattern when evaluating Terraform is to generate the plan as JSON and feed that structure to OPA to evaluate against the policies.

4. Practical Example: Blocking a Public S3 Bucket

Consider this resource, which anyone could write by mistake when copying an outdated blog example:

resource "aws_s3_bucket" "logs" {
  bucket = "app-logs-prod"
}

resource "aws_s3_bucket_public_access_block" "logs" {
  bucket = aws_s3_bucket.logs.id

  block_public_acls       = false
  block_public_policy     = false
  ignore_public_acls      = false
  restrict_public_buckets = false
}

A Rego policy to block this pattern, evaluating the JSON plan generated by terraform show -json:

package terraform.security

import future.keywords.in

deny[msg] {
    resource := input.resource_changes[_]
    resource.type == "aws_s3_bucket_public_access_block"

    change := resource.change.after

    some field in ["block_public_acls", "block_public_policy",
                   "ignore_public_acls", "restrict_public_buckets"]
    change[field] == false

    msg := sprintf(
        "resource '%s' allows public access (%s = false)",
        [resource.address, field],
    )
}

5. Running the Policy with Conftest

Conftest is a CLI that makes it easy to test structured files (JSON, YAML, Terraform plans) against Rego policies, without setting up OPA’s whole server infrastructure:

# Generate the plan in binary format and then as JSON
terraform plan -out=tfplan.binary
terraform show -json tfplan.binary > tfplan.json

# Evaluate the plan against the policies in the policy/ directory
conftest test --policy policy/ tfplan.json

If the policy from the previous step is violated, the output looks like this:

FAIL - tfplan.json - terraform.security - resource 'aws_s3_bucket_public_access_block.logs' allows public access (block_public_acls = false)

1 test, 0 passed, 1 failed, 0 warnings

conftest’s non-zero exit code is what lets you use this command as a CI gate: if it fails, the pipeline stops before reaching apply.

6. Sentinel as an Alternative

For those already using Terraform Cloud/Enterprise, Sentinel offers the same concept with native integration — policies run automatically between plan and apply, without setting up the conftest pipeline by hand:

import "tfplan/v2" as tfplan

public_s3_buckets = filter tfplan.resource_changes as _, rc {
    rc.type is "aws_s3_bucket_public_access_block" and
    rc.change.after.block_public_acls is false
}

main = rule {
    length(public_s3_buckets) is 0
}

The syntax is different from Rego, but the idea is identical: inspect the plan and refuse the apply if a security condition isn’t met. The choice between OPA and Sentinel tends to be less about technical capability and more about where the team already is: outside Terraform Cloud, OPA/Conftest is the lock-in-free option; inside it, Sentinel removes the integration step.

7. Where to Run the Policies in the Pipeline

Policy as Code only pays off if the check is mandatory, not optional. A typical GitHub Actions pipeline:

# .github/workflows/terraform.yml
jobs:
  plan-and-check:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: hashicorp/setup-terraform@v3

      - run: terraform init
      - run: terraform plan -out=tfplan.binary
      - run: terraform show -json tfplan.binary > tfplan.json

      - name: Install conftest
        run: |
          curl -fsSL https://github.com/open-policy-agent/conftest/releases/latest/download/conftest_linux_x86_64.tar.gz | tar xz
          sudo mv conftest /usr/local/bin

      - name: Evaluate security policies
        run: conftest test --policy policy/ tfplan.json

      # The apply only runs if the previous step doesn't fail
      - run: terraform apply -auto-approve tfplan.binary

Putting the check before apply, as a step that can fail the job, is what turns the policy from “documentation nobody reads” into “a barrier nobody can skip by accident”.

8. Conclusion

Policy as Code closes a gap that manual code review doesn’t cover well: ensuring, automatically and repeatably, that every resource created by IaC respects the organization’s security rules — without depending on the attention of whoever is reviewing the PR. OPA with Rego (via Conftest) and Sentinel solve the same problem with different integrations; what matters is that the check runs as a mandatory gate in the pipeline, not as a suggestion. In the next and final article of this series, we get into another governance pillar: how to design IAM permissions with the least privilege necessary — and how to audit, automatically, when that stops being true.


References:

  1. Open Policy Agent — Documentation
  2. Conftest — Documentation
  3. HashiCorp Sentinel — Documentation