Opscraft
Open Policy Agent · Lesson 6 of 9 · 3 min read

Shift-left: the same rules in CI with conftest

Admission control catches problems at deploy time. Running the same policies in CI catches them at PR time — faster feedback and fewer failed deployments.

Enlarge diagrampolicy repoRego + testsCI: conftestfails the PR earlycluster: Gatekeeperlast line of defencesecondsat deploy time
Figure 1. One policy repo, two enforcement points: conftest in the pull request and Gatekeeper at admission.
Swipe sideways to see all of it, or tap to open it full screen.

conftest runs Rego against YAML, JSON, HCL, Dockerfiles, INI, TOML and more. By default it looks in policy/ for rules named deny, violation or warn in package main:

# policy/k8s.rego
package main

import rego.v1

deny contains msg if {
    input.kind == "Deployment"
    not input.spec.template.spec.securityContext.runAsNonRoot
    msg := sprintf("%s: pods must set runAsNonRoot", [input.metadata.name])
}

warn contains msg if {
    input.kind == "Deployment"
    input.spec.replicas < 2
    msg := sprintf("%s: fewer than 2 replicas means no HA", [input.metadata.name])
}
kustomize build deploy/overlays/prod | conftest test -        # rendered manifests
conftest test Dockerfile --namespace docker                    # e.g. deny FROM ...:latest, USER root

Terraform plans:

terraform plan -out tf.plan
terraform show -json tf.plan > plan.json
conftest test plan.json --namespace terraform
package terraform

import rego.v1

deny contains msg if {
    some rc in input.resource_changes
    rc.type == "aws_s3_bucket_public_access_block"
    rc.change.after.block_public_acls == false
    msg := sprintf("%s must block public ACLs", [rc.address])
}

deny contains msg if {
    some rc in input.resource_changes
    rc.type == "aws_security_group_rule"
    rc.change.after.type == "ingress"
    some cidr in rc.change.after.cidr_blocks
    cidr == "0.0.0.0/0"
    rc.change.after.from_port <= 22
    rc.change.after.to_port >= 22
    msg := sprintf("%s opens SSH to the world", [rc.address])
}

Terraform Cloud/Enterprise has Sentinel (HashiCorp's policy language) and also supports OPA policies; open-source alternatives are conftest, Checkov and tfsec/Trivy (pre-written rules). OPA's advantage is one language everywhere.

The same Rego can be shared between conftest (CI) and Gatekeeper (admission) with a thin adapter for the different input shapes (input vs input.review.object).