TExcelTAD
Home › Secrets & Policy as Code: Vault, SOPS, OPA & Conftest › Conftest on Kubernetes Manifests

Conftest on Kubernetes Manifests

opa eval answers one question about one JSON document. Conftest wraps OPA for configuration files: it parses YAML, JSON, HCL, Dockerfiles, INI, TOML, XML and more into JSON, runs every policy in policy/ against every document, and reports with an exit code a pipeline can use.

Conftest convention Meaning
policy/ default policy directory (-p to change)
package main default namespace (--namespace x, or --all-namespaces)
deny, violation failures (exit 1)
warn warnings (exit 0, or 1 with --fail-on-warn)
exception names rules to skip for matching inputs
-d data/ extra data files, under data.
`-o table json

Checking a set of manifests

bash · try it yourself
mkdir -p policy deploy
cat > policy/workloads.rego <<'REGO'
package main

workload if input.kind in {"Deployment", "StatefulSet", "DaemonSet"}

pod_spec := input.spec.template.spec

deny_root contains msg if {
	workload
	not pod_spec.securityContext.runAsNonRoot
	msg := sprintf("%s/%s: set spec.template.spec.securityContext.runAsNonRoot: true", [input.kind, input.metadata.name])
}

deny_latest contains msg if {
	workload
	some c in pod_spec.containers
	not contains(c.image, "@sha256:")
	endswith(c.image, ":latest")
	msg := sprintf("%s/%s: container %q uses :latest", [input.kind, input.metadata.name, c.name])
}

warn_probes contains msg if {
	workload
	some c in pod_spec.containers
	not c.readinessProbe
	msg := sprintf("%s/%s: container %q has no readinessProbe", [input.kind, input.metadata.name, c.name])
}

# a reviewed exception: the legacy importer runs as root until it is rewritten (ticket LNK-142)
exception contains rules if {
	input.metadata.name == "legacy-importer"
	rules := ["root"]
}
REGO
cat > deploy/linkly.yaml <<'YAML'
apiVersion: apps/v1
kind: Deployment
metadata: {name: linkly}
spec:
  template:
    spec:
      securityContext: {runAsNonRoot: true}
      containers:
        - name: app
          image: ghcr.io/acme/linkly:1.4.2
          readinessProbe: {httpGet: {path: /readyz, port: 8080}}
---
apiVersion: v1
kind: Service
metadata: {name: linkly}
spec: {selector: {app: linkly}, ports: [{port: 80, targetPort: 8080}]}
YAML
cat > deploy/jobs.yaml <<'YAML'
apiVersion: apps/v1
kind: Deployment
metadata: {name: legacy-importer}
spec:
  template:
    spec:
      containers: [{name: importer, image: "ghcr.io/acme/importer:2.0.1"}]
---
apiVersion: apps/v1
kind: Deployment
metadata: {name: link-preview}
spec:
  template:
    spec:
      containers: [{name: preview, image: "ghcr.io/acme/preview:latest"}]
YAML
conftest test deploy/; echo "exit $?"
WARN - deploy/jobs.yaml - main - Deployment/legacy-importer: container "importer" has no readinessProbe
WARN - deploy/jobs.yaml - main - Deployment/link-preview: container "preview" has no readinessProbe
FAIL - deploy/jobs.yaml - main - Deployment/link-preview: set spec.template.spec.securityContext.runAsNonRoot: true
FAIL - deploy/jobs.yaml - main - Deployment/link-preview: container "preview" uses :latest
EXCP - deploy/jobs.yaml - main - data.main.exception[_][_] == "root"

12 tests, 7 passed, 2 warnings, 2 failures, 1 exception
exit 1
  • Conftest evaluates every rule whose name is deny, warn, violation or starts with deny_/warn_/violation_. Every YAML document is tested separately: 4 documents × 3 rules = 12 tests.
  • Rules named deny_<name> let an exception refer to <name>: the legacy importer's root rule shows as EXCP, while its missing probe still warns. Exceptions live in Git with a reason and a ticket, which is much better than disabling the check in the pipeline.
  • link-preview breaks two rules; both are reported, so one pipeline run shows everything to fix.

Rules across documents: --combine

Some mistakes only show up when you look at several objects together, like a Service whose selector matches no Deployment. --combine passes all documents as one input, a list of {path, contents}:

bash · try it yourself
mkdir -p policy
cat > policy/combined.rego <<'REGO'
package main

deployment_labels contains labels if {
	some doc in input
	doc.contents.kind == "Deployment"
	labels := doc.contents.spec.template.metadata.labels
}

deny contains msg if {
	some doc in input
	doc.contents.kind == "Service"
	selector := doc.contents.spec.selector
	not selects_something(selector)
	msg := sprintf("Service %s selects %v, which matches no Deployment's pod labels", [doc.contents.metadata.name, selector])
}

selects_something(selector) if {
	some labels in deployment_labels
	every k, v in selector { labels[k] == v }
}
REGO
cat > app.yaml <<'YAML'
apiVersion: apps/v1
kind: Deployment
metadata: {name: linkly}
spec: {template: {metadata: {labels: {app: linkly, tier: api}}}}
---
apiVersion: v1
kind: Service
metadata: {name: linkly}
spec: {selector: {app: linkly}}
---
apiVersion: v1
kind: Service
metadata: {name: linkly-metrics}
spec: {selector: {app: linky}}
YAML
conftest test --combine app.yaml
FAIL - Combined - main - Service linkly-metrics selects {"app": "linky"}, which matches no Deployment's pod labels

1 test, 0 passed, 0 warnings, 1 failure, 0 exceptions

The typo linky would have produced a Service with no endpoints and a confusing outage; here it is a failed check in the pull request.

Dockerfiles and other formats

Conftest picks a parser by file extension or name (--parser overrides it). A Dockerfile becomes a list of instructions:

bash · try it yourself
mkdir -p policy
cat > policy/docker.rego <<'REGO'
package main

deny contains msg if {
	some instr in input
	instr.Cmd == "user"
	instr.Value[0] in {"root", "0"}
	msg := "do not switch to USER root"
}

deny contains msg if {
	some instr in input
	instr.Cmd in {"env", "arg"}
	some v in instr.Value
	regex.match(`(?i)(password|secret|token|key)`, v)
	msg := sprintf("%s %s looks like a secret baked into the image; use a BuildKit secret mount", [upper(instr.Cmd), v])
}
REGO
cat > Dockerfile <<'DOCKER'
FROM golang:1.27 AS build
ARG GITHUB_TOKEN
RUN go build -o /linkly ./cmd/linkly
FROM gcr.io/distroless/static-debian12:nonroot
COPY --from=build /linkly /linkly
USER root
ENTRYPOINT ["/linkly"]
DOCKER
conftest test Dockerfile
FAIL - Dockerfile - main - ARG GITHUB_TOKEN looks like a secret baked into the image; use a BuildKit secret mount
FAIL - Dockerfile - main - do not switch to USER root

2 tests, 0 passed, 0 warnings, 2 failures, 0 exceptions

The same trick works for anything Conftest can parse: GitHub Actions workflows (YAML), .tf files (HCL2), nginx-style INI files. To see exactly what a policy receives, run conftest parse <file>.

Rendered manifests

Policies should check what will actually be applied: the rendered output of Helm or Kustomize, not the templates. Conftest reads standard input with -:

bash
helm template linkly ./chart -f values-prod.yaml | conftest test -
kustomize build overlays/prod | conftest test -

Run it in the same CI job that renders and validates with kubeconform (Rendering & Validating in CI).

Test yourself

What does a rule named deny_root enable in Conftest?

  1. Nothing special
  2. Exceptions can refer to it as root to skip it for matching inputs
  3. It only runs as root
  4. It becomes a warning

Why use --combine?

  1. To speed up tests
  2. To check relationships between documents, like a Service selector matching a Deployment
  3. To merge policies
  4. To combine warnings and failures

Which exit code does conftest test return when there are only warnings (no flags)?

  1. 0
  2. 1
  3. 2
  4. It depends on the number of warnings