Do you want to apply any policy to avoid any changes happen in Kubernetes cluster? Kyverno is the right tool to achieve it.

Kyverno - Its a policy engine for kubernetes, define and enforce policies so that cluster users can maintain standard mechanism.

In this blog, we will see how to install Kyverno in Kubernetes and define policy.

Requirements:

Kubernetes cluster greater than v1.14

Step 1: Install Kyverno on kubernetes using manifest.

# kubectl create -f https://raw.githubusercontent.com/kyverno/kyverno/master/definitions/release/install.yaml

Validate the installation,

# kubectl get all -n kyverno



Step 2:

Create a policy that without label "app" in pod it should not deploy in cluster.

#cat policy.yaml

apiversion: kyverno.io/v1
kind: clusterpolicy
metadata:
  name: require-app-label
spec:
  validationfailureaction: enforce
  rules:
  - name: check-for-app-label
    match:
      resources:
        kinds:
        - pod
    validate:
      message: "label `app` is required"
      pattern:
        metadata:
          labels:
            app: "?*"

# kubectl apply -f policy.yaml

Now policy is created, Hereafter if any deployment without label "app" it will not deploy in the cluster.

For more Policies : https://github.com/kyverno/policies/tree/main/best-practices

Step 3:

Create a sample pod deployment without label "app"

#vi nginx.yaml

apiVersion: v1
kind: Pod
metadata:
  name: webapp
  namespace: application
  labels:
    name: webapp
spec:
  containers:
  - name: webapp
    image: nginx

#  kubectl apply -f nginx.yaml


You can see the pod is not deployed and it is restricted by our policy.

Now add the label app and try it.

# vi nginx.yaml

apiVersion: v1
kind: Pod
metadata:
  name: webapp
  namespace: application
  labels:
    name: webapp
    app: webapp
spec:
  containers:
  - name: webapp
    image: nginx

# kubectl apply -f nginx.yaml


Now the pod is deployed. Similarly we can create our own custom policies and restrict the deployment in any cluster.

That's all, Kyverno is installed in Kubernetes cluster and tested a policy.


Reference : https://kyverno.io/docs/introduction/

Post a Comment

Previous Post Next Post