OPA (Open Policy Agent)

OPA (Open Policy Agent) is a policy engine that enforces compliance, security, and governance rules across cloud, Kubernetes, CI/CD pipelines, APIs, and infrastructure-as-code. In DevSecOps, OPA provides Compliance as Code, meaning all compliance rules are written, version-controlled, tested, and continuously enforced using automated pipelines. OPA ensures every deployment, change, and configuration meets organizational or regulatory standards.

What OPA Does in DevSecOps

OPA evaluates policies against incoming requests, configurations, or resources, then decides:

• allow
• deny
• warn
• modify (using OPA Gatekeeper or OPA bundles)

OPA can enforce:

• Kubernetes governance
• CI/CD compliance
• image registry rules
• infrastructure-as-code validation
• cloud access policies
• API authorization
• microservice security rules

OPA replaces manual reviews with automated, codified checks.

How OPA Works

OPA uses a declarative policy language called Rego.
Policies are evaluated against input JSON.

Flow:

  1. System sends input (e.g., Kubernetes manifest, API request).

  2. OPA loads policies from its policy bundles.

  3. OPA runs Rego rules to determine compliance.

  4. OPA returns allow/deny/warn decisions.

OPA evaluates compliance continuously.

OPA Deployment Models

OPA Standalone

Runs as a sidecar or service validating API requests.

OPA Gatekeeper for Kubernetes

Admission controller validating manifests before creation.

OPA in CI/CD

Validates Terraform, Kubernetes YAML, Helm, and pipeline configs.

OPA in API Authorization

Validates who can access which service endpoints.

OPA in Cloud Policies

Validates cloud configuration drift.

OPA can run everywhere because it is lightweight and fast.


Understanding Rego Policies

Rego policies define rules using:

• allow/deny logic
• constraints
• validation checks
• pattern matching
• JSON input processing

Example deny rule:

deny[msg] {
  input.spec.containers[_].securityContext.privileged == true
  msg := "Privileged containers are not allowed"
}

OPA returns:

[
  "Privileged containers are not allowed"
]

OPA denies the request.

Common Compliance Rules Enforced Using OPA

• all pods must run as non-root
• disallow privileged containers
• enforce label standards
• block images from unapproved registries
• require resource limits
• block public S3 buckets
• enforce encryption on cloud storage
• ensure Terraform uses secure configurations
• restrict CI pipelines from executing unverified scripts

OPA enforces security at every stage.

OPA Gatekeeper in Kubernetes

Gatekeeper integrates OPA with Kubernetes admission controllers. It uses:

• ConstraintTemplates – define Rego logic
• Constraints – apply rules to cluster resources

Gatekeeper enforces compliance pre-deployment.

Example:

apiVersion: templates.gatekeeper.sh/v1
kind: ConstraintTemplate
metadata:
  name: k8snonroot
spec:
  crd:
    spec:
      names:
        kind: K8sNonRoot
  targets:
    - target: admission.k8s.gatekeeper.sh
      rego: |
        package k8snonroot
        violation[{"msg": msg}] {
          input.review.object.spec.containers[_].securityContext.runAsNonRoot != true
          msg := "Containers must run as non-root"
        }

Then define actual constraint:

apiVersion: constraints.gatekeeper.sh/v1beta1
kind: K8sNonRoot
metadata:
  name: enforce-nonroot
spec:
  match:
    kinds:
      - apiGroups: [""]
        kinds: ["Pod"]

Gatekeeper blocks pods that violate the rule.


Full-Length Practical Section

Hands-on tasks for learning OPA deeply with real DevSecOps compliance workflows.


Practical 1: Install OPA CLI

brew install opa

Verify:

opa version

Practical 2: Test Simple Rego Policy Locally

Create file:

package example

deny[msg] {
  input.kind == "Pod"
  msg := "Policy triggered"
}

Test with:

opa eval --input input.json --data policy.rego "data.example.deny"

Practical 3: Validate Kubernetes YAML in CI

Input:

kubectl apply --dry-run=client -o json -f pod.yaml > input.json

Run OPA:

opa eval --format pretty --data policy.rego --input input.json "data"

OPA validates manifests before deployment.


Practical 4: Block Privileged Containers With Rego

Policy:

deny[msg] {
  input.spec.containers[_].securityContext.privileged == true
  msg := "Privileged containers are forbidden"
}

Test locally.


Practical 5: Enforce Non-root User

deny[msg] {
  sc := input.spec.containers[_].securityContext
  not sc.runAsNonRoot
  msg := "Containers must run as non-root"
}

Practical 6: Validate Resource Limits

deny[msg] {
  container := input.spec.containers[_]
  not container.resources.limits.cpu
  msg := "CPU limit required"
}

Enforce resource policies.


Practical 7: Enforce Allowed Registries

deny[msg] {
  image := input.spec.containers[_].image
  not startswith(image, "registry.mycompany.com/")
  msg := "Image must come from approved registry"
}

Practical 8: Install OPA Gatekeeper in Kubernetes

kubectl apply -f https://raw.githubusercontent.com/open-policy-agent/gatekeeper/master/deploy/gatekeeper.yaml

Verify:

kubectl get pods -n gatekeeper-system

Practical 9: Create ConstraintTemplate

Define custom rule file:

kind: ConstraintTemplate
metadata:
  name: blockprivileged
...

Embed Rego rule.


Practical 10: Create Constraint Using Template

kind: BlockPrivileged
spec:
  match:
    kinds:
      - apiGroups: [""]
        kinds: ["Pod"]

Gatekeeper enforces blocking.


Practical 11: Test Deployment of Violating Pod

Attempt:

kubectl apply -f privileged-pod.yaml

Gatekeeper denies creation.


Practical 12: Enforce Labels for Compliance

Rego policy:

deny[msg] {
  not input.metadata.labels.owner
  msg := "owner label required"
}

Practical 13: Enforce Terraform Security Using OPA

Convert Terraform plan to JSON:

terraform show -json plan.out > plan.json

OPA validates:

opa eval --data tf-policy.rego --input plan.json "data"

Examples:

• block public S3 buckets
• require encryption
• enforce IAM roles


Practical 14: Use OPA in CI/CD Pipelines

GitHub Actions example:

- run: opa eval --data policy.rego --input kubespec.json "data.deny"

Pipeline fails if policy denies.


Practical 15: Enforce Policy Bundles

Package policies:

opa build policy.rego

Deploy as bundle to cluster.


Practical 16: Audit Existing Kubernetes Resources

kubectl get deploy -A -o json | opa eval --input - --data policy.rego "data.deny"

Find non-compliant deployments.


Practical 17: Use Gatekeeper Audit Mode

kubectl get k8snonroot --all-namespaces -o yaml

Shows non-compliant existing resources.


Practical 18: Manage Policy Lifecycle With GitOps

Push policies to:

• Argo CD
• Flux

Policies automatically sync to clusters.


Practical 19: Write Policy for Encrypted Cloud Buckets

Rego example:

deny[msg] {
  bucket := input.resource
  bucket.encryption.enabled != true
  msg := "Bucket must have encryption enabled"
}

Practical 20: Build Full Compliance-as-Code Architecture

Architecture includes:

• OPA CLI for local validation
• OPA Gatekeeper for Kubernetes enforcement
• OPA policies integrated with CI/CD
• Terraform compliance checks using OPA
• GitOps-managed policy bundles
• SIEM correlation for policy violations
• policy audit reporting
• automated remediation workflows
• end-to-end compliance checks for cloud, code, IaC, and workloads

This creates a complete, consistent, and automated compliance-as-code ecosystem.


Intel Dump

• OPA enforces compliance as code across Kubernetes, cloud, IaC, CI/CD, and APIs
• policies written in Rego define allow/deny logic
• Gatekeeper integrates OPA with Kubernetes admission control
• practicals include writing Rego policies, validating manifests, Terraform checks, deploying Gatekeeper, auditing clusters, CI/CD integration, and complete compliance architecture

HOME LEARN COMMUNITY DASHBOARD