Modern QA2026Custom Validation with OPA Gatekeeper — tiles
Log inJoin
33 / 75 · 08 Infrastructure as Code Testing · Kubernetes Manifest Validation← prev⊞ allnext →☰ Read as one page

6.4Custom Validation with OPA Gatekeeper

For organization-specific rules that go beyond standard tools, deploy OPA Gatekeeper as a Kubernetes admission controller:

# constraint-template.yaml
apiVersion: templates.gatekeeper.sh/v1
kind: ConstraintTemplate
metadata:
  name: k8snolatestimage
spec:
  crd:
    spec:
      names:
        kind: K8sNoLatestImage
  targets:
    - target: admission.k8s.gatekeeper.sh
      rego: |
        package k8snolatestimage

        violation[{"msg": msg}] {
          container := input.review.object.spec.template.spec.containers[_]
          endswith(container.image, ":latest")
          msg := sprintf("Container '%s' uses :latest tag. Pin a specific version.", [container.name])
        }

        violation[{"msg": msg}] {
          container := input.review.object.spec.template.spec.containers[_]
          not contains(container.image, ":")
          msg := sprintf("Container '%s' has no image tag. Pin a specific version.", [container.name])
        }

---
# constraint.yaml
apiVersion: constraints.gatekeeper.sh/v1beta1
kind: K8sNoLatestImage
metadata:
  name: no-latest-image
spec:
  match:
    kinds:
      - apiGroups: ["apps"]
        kinds: ["Deployment", "StatefulSet", "DaemonSet"]
    namespaces:
      - production
      - staging