open-policy-agent / gatekeeper-library

📚 The OPA Gatekeeper policy library
https://open-policy-agent.github.io/gatekeeper-library
Apache License 2.0
617 stars 316 forks source link

K8sRequiredResources ConstraintTemplate doesn't work properly #522

Closed rkosyk closed 1 month ago

rkosyk commented 1 month ago

It looks like K8sRequiredResources ConstraintTemplate doesn't work properly

For example this constraint: https://github.com/open-policy-agent/gatekeeper-library/blob/master/library/general/containerresources/samples/container-must-have-limits-and-requests/constraint.yaml

apiVersion: constraints.gatekeeper.sh/v1beta1
kind: K8sRequiredResources
metadata:
  name: container-must-have-limits-and-requests
spec:
  match:
    kinds:
      - apiGroups: [""]
        kinds: ["Pod"]
  parameters:
    limits:
      - cpu
      - memory
    requests:
      - cpu
      - memory

allows the creation of pod without container resources requests defined, as shown in this example:

apiVersion: v1
kind: Pod
metadata:
  name: opa-disallowed
  labels:
    owner: me.agilebank.demo
spec:
  containers:
    - name: opa
      image: openpolicyagent/opa:0.9.2
      args:
        - "run"
        - "--server"
        - "--addr=localhost:8080"
      resources:
        limits:
          memory: "2Gi"
          cpu: "100m"

It is expected that the creation of such a pod should be disallowed.

rkosyk commented 1 month ago

Closing this issue because I have found an explanation for this - If you specify a CPU limit for a Container but do not specify a CPU request, Kubernetes automatically assigns a CPU request that matches the limit. https://kubernetes.io/docs/tasks/configure-pod-container/assign-cpu-resource/#if-you-specify-a-cpu-limit-but-do-not-specify-a-cpu-request