unable to use opa gatekeeper for denying pods with latest tags in a specific namespace (prod) on kubernetes

862 Views Asked by At

i'm new in OPA policies and need to deny pods running in my cluster with containers that have latest tag in its images, this must be denied just for prod namespace, the problem that i have is whatever the namespace used, the pods will be denied if they're created with latest tag in their images!!!!!, i'm i did a mistake here? this is my constraint template:

apiVersion: templates.gatekeeper.sh/v1beta1
kind: ConstraintTemplate
metadata:
 name: k8srequiredtags
spec:
 crd:
  spec:
   names:
    kind: k8srequiredtags
   validation:
    # Schema for the `parameters` field
    openAPIV3Schema:
     properties:
      image:
       type: string
 targets:
  - target: admission.k8s.gatekeeper.sh
    rego: |
     package k8srequiredtags
     violation[{"msg": msg, "details": {"Registry should be": required}}] {
      input.review.object.kind == "Pod"
      some i
      image := input.review.object.spec.containers[i].image
      required := input.parameters.registry
      contains(image, required)
      msg := sprintf("The image tag is not for the production environment, thanks to use specified tags instead of : %v", [image])
      }

and here's my constraint :

apiVersion: constraints.gatekeeper.sh/v1beta1
kind: k8srequiredtags
metadata:
 name: deny-latest-tags
spec:
 match:
  kinds:
   - apiGroups: [""]
     kinds: ["Pod"]
     namespace: ["prod"]
 parameters:
  registry: "latest"
1

There are 1 best solutions below

0
On

Great that you are trying OPA, and gatekeeper.

By quickly looking at your code there are some things I would change:

  • Since you are passing "Pods" as a kind, in you Constraint, there is no need to filter it in your Template. You are only passing in resources of kind: Pod.
  • You violation rule defined the object "input.review.object.spec.containers[i].image". This object is referring to the whole image attribute of the Pod resource. So, it would include /:. So, this would probably never only be "latest". It would probably be a reference to a URL to a docker image. You probably need to parse out the tag in order to use it for comparison.
  • Regarding the issue you posted about namespaces: I think it is related to the facts that the match filter looks for a filter attribute called: "namespaces", not "namespace" [https://github.com/open-policy-agent/gatekeeper/blob/master/README.md#constraints].

Good luck.