Skip to main content
In this hands-on tutorial, you’ll integrate OPA Conftest into a Jenkins pipeline to enforce custom policy-as-code for Kubernetes Deployments and Services. Scanning your manifests before they reach the cluster helps prevent misconfigurations and potential security vulnerabilities.
The image is a presentation slide titled "HANDS ON" about Kubernetes vulnerabilities, mentioning OPA Conftest, Kubesc, and Trivy. It includes a meme of a boy excitedly looking at a computer with the text "I CAN'T BELIEVE IT IT'S DEMO TIME."

Prerequisites

  • Jenkins server with Docker installed
  • Kubernetes cluster and kubectl configured
  • OPA Conftest CLI available locally or via Docker
Ensure your kubeconfig credentials are stored in Jenkins (e.g., under credentialsId: 'kubeconfig') before starting.

Jenkins Pipeline Stages

Add a vulnerability scan stage between the Docker build and Kubernetes deployment:

Defining the OPA Policy

Create opa-k8s-security.rego at the root of your project:

Running Conftest

From your project directory, run:
If any policy is violated, Conftest exits with a non-zero code and prints the error. Your Jenkins pipeline will fail until you address the violation.
Example failure output:

Fixing Policy Violations

1. Enforce runAsNonRoot

Update your Deployment spec to include a securityContext:
Re-run the Conftest command to confirm that all tests pass.

2. Specify Numeric User (Optional)

If you encounter a CreateContainerConfigError due to a non-numeric user, add runAsUser:
Commit, push, and trigger a new build.

Verifying Deployment

After a successful pipeline run, validate your resources:
You should see the Deployment and Service running without errors.

Watch Video