Lab: Deploy Kyverno and Enforce costcenter
Label on Pods
Objective
- Deploy Kyverno in your cluster
- Create a Kyverno policy that validates all pods have a
costcenter
label - Test pod creation with and without the label
Prerequisites
- A running Kubernetes cluster (Minikube, Kind, etc.)
kubectl
installed- Cluster-admin access
π Lab Structure
kyverno-lab/
βββ policies/
β βββ require-costcenter-label.yaml
βββ test/
βββ good-pod.yaml
βββ bad-pod.yaml
Install Kyverno
kubectl create -f https://github.com/kyverno/kyverno/releases/latest/download/install.yaml
Verify itβs running:
kubectl get pods -n kyverno
Create the Required Label Policy
π policies/require-costcenter-label.yaml
apiVersion: kyverno.io/v1
kind: ClusterPolicy
metadata:
name: require-costcenter-label
spec:
validationFailureAction: Enforce
rules:
- name: check-costcenter-label
match:
resources:
kinds:
- Pod
validate:
message: "All pods must have a 'costcenter' label."
pattern:
metadata:
labels:
costcenter: "?*"
Apply the policy:
kubectl apply -f policies/require-costcenter-label.yaml
Test the Policy
Good Pod
π test/good-pod.yaml
apiVersion: v1
kind: Pod
metadata:
name: good-nginx
labels:
costcenter: devops
spec:
containers:
- name: nginx
image: nginx
Apply:
kubectl apply -f test/good-pod.yaml
π’ Should succeed.
β Bad Pod (Missing costcenter
)
π test/bad-pod.yaml
apiVersion: v1
kind: Pod
metadata:
name: bad-nginx
spec:
containers:
- name: nginx
image: nginx
Apply:
kubectl apply -f test/bad-pod.yaml
π΄ Should be rejected with:
Error from server: admission webhook ... denied the request: All pods must have a 'costcenter' label.
Summary
Component | Description |
---|---|
Kyverno | Validating admission controller |
ClusterPolicy | Enforces label presence on pod creation |
costcenter label | Required label to pass policy check |
Cleanup
kubectl delete -f test/
kubectl delete -f policies/require-costcenter-label.yaml
kubectl delete -f https://github.com/kyverno/kyverno/releases/latest/download/install.yaml