Kubernetes ValidatingAdmissionPolicy basic example

To use this we need to create a "ValidatingAdminisionPolicy" and "ValidatingAdmissionPolicyBinding". 

This example will prevent pod from being created if it des not have "label called environment".

apiVersion: admissionregistration.k8s.io/v1
kind: ValidatingAdmissionPolicy
metadata:
  name: "require-env-label"
spec:
  failurePolicy: Fail
  matchConstraints:
    resourceRules:
    - apiGroups:   [""]
      apiVersions: ["v1"]
      operations:  ["CREATE", "UPDATE"]
      resources:   ["pods"]
  validations:
    - expression: "has(object.metadata.labels) && 'environment' in object.metadata.labels"
      message: "The 'environment' label is required for all Pods."

And then we have ValidatingAdmissionPolicyBinding


apiVersion: admissionregistration.k8s.io/v1
kind: ValidatingAdmissionPolicyBinding
metadata:
  name: "require-env-label-binding"
spec:
  policyName: "require-env-label"
  validationActions: [Deny] # This makes it a hard block
  matchResources:
    namespaceSelector: {} # This matches ALL namespaces

Then if we try to run something funny like this 

kubectl run web-test --image=nginx 

We will get an error:


And then we run 

kubectl run web-test --image=nginx --labels="environment=production,tier=frontend"



And our pod gets created. 


Comments

Popular posts from this blog

vllm : Failed to infer device type

android studio kotlin source is null error

NodeJS: Error: spawn EINVAL in window for node version 20.20 and 18.20