In this lesson, you will learn how to automate security and compliance validation by treating your infrastructure configuration files as code that must pass specific policy tests before deployment.
Shifting Security Left
When infrastructure is defined declaratively (e.g., using Terraform or Kubernetes manifests), configuration errors—like an S3 bucket left open to the public or a container running with root privileges—can introduce significant vulnerabilities. Instead of discovering these issues during manual audits or post-deployment security scans, we use Policy as Code (PaC) to catch them during the CI/CD pipeline.
By treating security rules as machine-readable code, you enable consistent enforcement across all environments. If a configuration violates a defined security policy, the CI/CD pipeline fails, preventing the deployment entirely.
Implementing Policy with OPA
Open Policy Agent (OPA) is the industry standard for this task. You write policies in a language called Rego, which defines the "rules" your infrastructure must follow.
Consider a simple policy that mandates all Kubernetes containers must have a non-root user defined:
package main
# Deny deployments if securityContext.runAsNonRoot is not true
deny[msg] {
input.kind == "Deployment"
not input.spec.template.spec.securityContext.runAsNonRoot == true
msg := "Security violation: Containers must run as non-root."
}
In your CI pipeline, you would run an evaluation tool (like conftest) against your manifests:
- Plan/Generate: Your infrastructure tool creates the deployment manifest.
- Evaluate: The CI runner executes the OPA policies against the manifest.
- Gate: If the evaluation returns a
denyresult, the pipeline exits with an error, blocking the deployment and notifying the developer.
This approach transforms security from a reactive, human-led checklist into a proactive, automated gatekeeper. By integrating these checks into your pipeline, you ensure that every change adheres to organizational compliance standards without slowing down velocity, provided the feedback loops are fast and actionable.
Key Takeaway: Policy as Code moves compliance out of human review and into the automated CI/CD pipeline, ensuring that only infrastructure configurations meeting your security standards reach production.