Open Policy Agent (OPA) and Conftest: Automating Kubernetes and Terraform Compliance in CI/CD

Security tutorial - IT technology blog
Security tutorial - IT technology blog

Comparing Approaches: Shifting Security Left

Six months ago, our infrastructure outgrew our review process. We were running 14 AWS accounts managed by Terraform alongside 45 microservices on Amazon EKS. Every pull request forced senior engineers to slog through hundreds of lines in YAML manifests and Terraform plans. They had to manually catch basic mistakes: missing CPU requests, wildcard security group rules, and containers running as root.

Catching misconfigurations during a Friday afternoon code review is unreliable. Human error is inevitable when reviewing raw diffs under deadline pressure. We needed deterministic, automated policy enforcement inside GitHub pull requests before any plan reached an apply step.

We evaluated three common strategies to solve this:

  • Specialized Linters (TFLint, Kube-score, Hadolint): Linters run quickly and require minimal configuration. But they operate in silos. TFLint knows nothing about Kubernetes manifests, and Kube-score cannot parse cloud infrastructure. More importantly, static linters cannot easily enforce organization-specific rules, such as requiring specific cost-center tags across all S3 buckets.
  • Runtime Admission Controllers (OPA Gatekeeper, Kyverno): Validating manifests at deployment time using Kubernetes Admission Webhooks protects running clusters. However, developers only see these failures after pushing code, passing CI, and waiting for an ArgoCD sync. Getting rejected that late wastes time and context-switches developers away from feature work.
  • Policy-as-Code via Conftest and OPA: Conftest packages the Open Policy Agent engine into a standalone CLI tailored for structured files (YAML, JSON, HCL, Dockerfiles). It decouples policy logic from live infrastructure. This lets engineers run identical compliance checks locally on their laptops and inside CI pipelines.

We chose Conftest because it validates pull requests directly without needing ephemeral test clusters.

Production Realities: 6 Months Later

Integrating Conftest into our GitHub Actions pipelines solved our visibility issues, though not without a few growing pains.

What Worked Well

  • A Single Policy Language: Rego handles Kubernetes deployments, Helm templates, Terraform plan JSON, and GitHub Actions workflow files. Learning one query language replaced maintaining five disconnected linters.
  • Sub-Second PR Feedback: Validations finish in roughly 2.8 seconds on our standard runners. Developers get an instant, human-readable terminal message showing the exact file, failing resource, and required fix.
  • Native Unit Testing: Running conftest verify executes mock-driven test suites against our policies. This kept us from accidentally shipping broken security constraints to active feature branches.

The Practical Pain Points

  • Rego’s Steep Syntax Curve: Rego is a declarative query language based on Datalog. Engineers used to Go, Python, or TypeScript often struggle with set comprehension, rule indexing, and the absence of mutable state and standard loops.
  • Nested Terraform Plan Schemas: Inspecting raw .tf files fails to evaluate computed values and modules. While compiled Terraform JSON (terraform show -json) is accurate, navigating its deeply nested resource_changes blocks requires reusable Rego helper functions.

Architecture and Policy Organization

Treat compliance policies with the same engineering standards as your backend services. To keep rules DRY and easy to maintain across 30+ service repositories, we organized our tooling into three components:

  • Central Policy Repository: All Rego policies live in a single repository ([email protected]:example/cloud-policies.git).
  • Versioned OCI Artifacts: Conftest can push and pull policies directly to OCI registries like AWS ECR or GitHub Packages. Our central CI builds, runs unit tests, and tags policy bundles (for example, conftest push ghcr.io/example/policies/k8s:v1.4.0).
  • Dual-Tier Severities: We split checks into deny (blocks the PR merge on critical risks like open SSH ingress or privileged pods) and warn (non-blocking notices for missing team ownership tags or unset memory limits).

Step-by-Step Implementation Guide

Follow these steps to set up Conftest, write practical Rego policies, and add them to a CI pipeline.

1. Installing Conftest

Install the Conftest binary on your local machine or inside CI runner base images:

CONFTEST_VERSION="0.56.0"
curl -LO "https://github.com/open-policy-agent/conftest/releases/download/v${CONFTEST_VERSION}/conftest_${CONFTEST_VERSION}_Linux_x86_64.tar.gz"
tar -xzf conftest_${CONFTEST_VERSION}_Linux_x86_64.tar.gz
sudo mv conftest /usr/local/bin/
conftest --version

2. Enforcing Kubernetes Workload Guardrails

The following rules prevent containers from running in privileged mode or as root. Save this policy to policy/k8s/security.rego:

package main

import future.keywords.in

# Helper to extract containers from Kubernetes workloads
containers[container] {
    some container in input.spec.template.spec.containers
}

# Rule 1: Block privileged execution
deny[msg] {
    input.kind in ["Deployment", "StatefulSet", "DaemonSet"]
    some container in containers
    container.securityContext.privileged == true
    msg := sprintf("Container '%v' in %v '%v' must not run in privileged mode.", [container.name, input.kind, input.metadata.name])
}

# Rule 2: Require non-root users
deny[msg] {
    input.kind in ["Deployment", "StatefulSet", "DaemonSet"]
    some container in containers
    not container.securityContext.runAsNonRoot == true
    msg := sprintf("Container '%v' in %v '%v' must set securityContext.runAsNonRoot to true.", [container.name, input.kind, input.metadata.name])
}

# Rule 3: Flag missing resource limits
warn[msg] {
    input.kind in ["Deployment", "StatefulSet", "DaemonSet"]
    some container in containers
    not container.resources.limits
    msg := sprintf("Container '%v' in %v '%v' has no resource limits defined.", [container.name, input.kind, input.metadata.name])
}

Validate your manifest locally against these rules:

conftest test deployment.yaml --policy policy/k8s/

3. Enforcing Terraform Security Baselines

Generate a JSON representation of your execution plan. This gives OPA access to fully resolved module variables and resource attributes:

terraform plan -out=tfplan.binary
terraform show -json tfplan.binary > tfplan.json

Create policy/terraform/aws_security.rego to block unrestricted SSH access (port 22) and catch unencrypted S3 buckets:

package main

import future.keywords.in

# Helper to filter planned resource creations or updates
resource_changes[res] {
    some res in input.resource_changes
    res.change.actions[_] in ["create", "update"]
}

# Rule 1: Disallow public SSH access (0.0.0.0/0 on port 22)
deny[msg] {
    some res in resource_changes
    res.type == "aws_security_group"
    some rule in res.change.after.ingress
    rule.from_port <= 22
    rule.to_port >= 22
    "0.0.0.0/0" in rule.cidr_blocks
    msg := sprintf("Security Group '%v' allows SSH (port 22) from 0.0.0.0/0.", [res.address])
}

# Rule 2: Ensure S3 buckets enforce server-side encryption
deny[msg] {
    some res in resource_changes
    res.type == "aws_s3_bucket"
    not res.change.after.server_side_encryption_configuration
    msg := sprintf("S3 Bucket '%v' must configure server_side_encryption_configuration.", [res.address])
}

Test the plan output:

conftest test tfplan.json --policy policy/terraform/

4. Wiring Conftest into GitHub Actions

Add this pipeline configuration to .github/workflows/policy-check.yml to run validations automatically against every incoming pull request:

name: Compliance Checks

on:
  pull_request:
    branches: [main]

jobs:
  validate:
    runs-on: ubuntu-latest
    steps:
      - name: Checkout Source
        uses: actions/checkout@v4

      - name: Install Conftest
        run: |
          CONFTEST_VERSION="0.56.0"
          curl -LO "https://github.com/open-policy-agent/conftest/releases/download/v${CONFTEST_VERSION}/conftest_${CONFTEST_VERSION}_Linux_x86_64.tar.gz"
          tar -xzf conftest_${CONFTEST_VERSION}_Linux_x86_64.tar.gz
          sudo mv conftest /usr/local/bin/

      - name: Validate Kubernetes Manifests
        run: |
          conftest test manifests/ \
            --policy policy/k8s/ \
            --all-namespaces \
            --output table

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

      - name: Generate and Check Terraform Plan
        env:
          AWS_DEFAULT_REGION: us-east-1
        run: |
          cd terraform/
          terraform init -backend=false
          terraform plan -out=tfplan.binary
          terraform show -json tfplan.binary > tfplan.json
          conftest test tfplan.json --policy ../policy/terraform/ --output table

5. Writing Policy Tests

Just like standard application code, compliance checks break when modified without regression tests. Create policy/k8s/security_test.rego:

package main

test_privileged_container_denied {
    sample_manifest := {
        "kind": "Deployment",
        "metadata": {"name": "insecure-workload"},
        "spec": {
            "template": {
                "spec": {
                    "containers": [{
                        "name": "app",
                        "securityContext": {"privileged": true, "runAsNonRoot": true}
                    }]
                }
            }
        }
    }
    r := deny with input as sample_manifest
    count(r) > 0
}

test_compliant_container_allowed {
    sample_manifest := {
        "kind": "Deployment",
        "metadata": {"name": "secure-workload"},
        "spec": {
            "template": {
                "spec": {
                    "containers": [{
                        "name": "app",
                        "securityContext": {"privileged": false, "runAsNonRoot": true}
                    }]
                }
            }
        }
    }
    r := deny with input as sample_manifest
    count(r) == 0
}

Run your test suite:

conftest verify --policy policy/k8s/

Decoupling policies from runtime clusters turns ambiguous security guidelines into concrete code. Reviewers spend less time policing boilerplate syntax and more time discussing architectural trade-offs, while developers catch mistakes before code ever leaves their branch.

Share: