Policy as Code in CI/CD with OPA
Treat pipeline rules as code using Open Policy Agent (OPA) to automate guardrails. Instead of scripts, write declarative policies to check test coverage or validate dependency licenses.
WHY IT EXISTS CI/CD pipelines often accumulate complex, hard-to-maintain scripts for enforcing organizational rules. These scripts become a source of pipeline fragility and technical debt. Policy as Code was created to replace them with a declarative, version-controlled system for defining and enforcing guardrails automatically.
THE MENTAL MODEL Think of Policy as Code as a linter for your entire pipeline. Just as a code linter checks for style and errors, a policy engine like Open Policy Agent (OPA) checks pipeline artifacts—configurations, test results, dependencies—against a set of rules you define as code. It answers the question, "Does this change comply with our rules?"
HOW IT WORKS OPA's command-line tool, opa eval, is the core component. It ingests JSON or YAML data, which is often piped from another tool's output via standard input. OPA then evaluates this data against a policy you've written. If the policy is violated, opa eval can exit with a non-zero status code using flags like --fail or --fail-defined, which fails the CI/CD job. This provides a clear pass/fail signal that integrates into any pipeline.
WHEN TO USE IT OPA is a flexible tool for custom checks that are difficult to implement otherwise. Use it for repository governance, like ensuring commit messages follow a specific format. Use it for software supply chain validation by checking package.json or go.mod for unapproved licenses. It can also perform dynamic tasks like test selection, determining which tests to run based on which files have changed, thus optimizing CI runtime.
WHEN NOT TO USE IT Avoid using the general-purpose opa eval command for validating static configuration files, especially Infrastructure as Code (IaC). A purpose-built tool from the OPA ecosystem, Conftest, is the better choice. Conftest is designed to parse many formats like HCL (Terraform) and Jsonnet that opa eval does not support natively. Use opa eval for runtime data and integrating different tools that output JSON or YAML.
ONE CANONICAL EXAMPLE In a GitHub Actions workflow, you can enforce a minimum test coverage. First, you run your tests and pipe the JSON output to OPA. The OPA command then checks if any result shows coverage below a threshold. my_test_command --json | opa eval --fail-defined --stdin-input 'input.results[_].coverage < 0.7' This command reads the JSON from stdin, evaluates the policy, and the --fail-defined flag causes the step to fail if any test result has coverage under 70%, stopping the pipeline.
Read the original → openpolicyagent.org
Get five bites like this every day.
Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.