Skip to main content

Command Palette

Search for a command to run...

Kyverno For Beginners ⎈

Updated
6 min read
Kyverno For Beginners ⎈
Y
Co-Organizer Cloud Native Nashik | OSS Advocate 🥑| Conference Speaker | Kubernetes | Blogger Extraordinaire

Hey Everyone, welcome to the new blog. In today's blog we are going to learn about Kyverno. So without wasting time let's get started.

What Is Kyverno?

As Per The Official Documentation Of Kyverno, It Is Defined As Follows:

  • Kyverno is a policy engine for Kubernetes. Policies are treated as Kubernetes resources in Kyverno, and no new language is needed to author policies. This enables the use of well-known tools like kubectl, git, and kustomize to manage policies. Kyverno policies can validate, mutate, and generate Kubernetes resources along with enforcing OCI image supply chain security. The Kyverno CLI can be utilized to test policies and validate resources as part of a CI/CD pipeline.

But What Are All These "Policies" We're Discussing? For Ease Let's Take An Example:

  • We all have been to universities once in our life, some of us might be studying it now and we have certain rules which we need to remember while studying in the university. Rules may be interpreted as policies in "Kubernetes" university. Therefore if you need to restrict/validate/make compulsory some properties, or characteristics your deployment must, or mustn't have, you can define that using Policies and Kyverno assists us in the policies creation which authenticate your deployment and report errors when the requirement does not match. So as you would probably know, this lets you have complete mastery over what happens in your deployment and whether or not it complies with the guidelines that you have laid down.

Architecture of Kyverno

Let's examine the architecture. Although it is not at all necessary to know each aspect of architecture but knowing where all things go and how the workflow goes can assist you in visualizing and executing better. Let's examine the images below.

As noticed that Kyverno plays a middleman role when you are attempting to deploy the manifest files to your clusters. It checks it and after passing applies it to the asked section in the deployment. Let's try it.

Command Cheatsheets

Here now we are going to deploy a simple nginx container. But now we don't want :latest image of nginx so we won't be permitted to deploy if image contains :latest tag and allow only if any other tag is :1.14.2 so let's begin.

  1. Firstly we will be utilizing helm within this tutorial therefore it is vital that you already have helm installed. Then go ahead and provision a Kubernetes cluster on any cloud provider of your choice, here in this tutorial I will be utilizing minikube.

  2. Now let's add Kyverno repository to the helm. Run the following command in terminal.

     helm repo add kyverno https://kyverno.github.io/kyverno/
    
  3. We have to now add Kyverno to our deployment cluster. Run the following 2 commands.

     # This is not mandatory command, this installs the pods security standards implemented by Kyverno. I have included it because it can be valuable practice in long run :)
     helm install kyverno-policies kyverno/kyverno-policies -n kyverno
    
     helm install kyverno kyverno/kyverno -n kyverno --create-namespace
    
     # Output for the above command:
     NAME: kyverno
     LAST DEPLOYED: Tue Dec 20 14:31:48 2022
     NAMESPACE: kyverno
     STATUS: deployed
     REVISION: 1
     NOTES:
     Chart version: 2.6.5
     Kyverno version: v1.8.5
    
     Thank you for installing kyverno! Your release is named kyverno.
    
  4. You can verify if it's successfully added by running the following kubectl command.

     kubectl get deploy -n kyverno
    
     NAME      READY   UP-TO-DATE   AVAILABLE   AGE
     kyverno   1/1     1            1           98s
    

If you get this then you have successfully installed Kyverno and you are ready to work with it.

Creating, Testing & Managing Policies

  1. Now make a folder called Kyverno in your computer and include files by the name of nginx.yml which will be our deployment file and my-policy.yml which will include the policy which we are trying to enforce. Include the below yml config code in it.

    -- This is code for nginx.yml (Here observe the image tag is 1.14.2).

apiVersion: apps/v1
kind: Deployment
metadata:
  name: nginx-deployment
  labels:
    app: nginx
spec:
  replicas: 1
  selector:
    matchLabels:
      app: nginx
  template:
    metadata:
      labels:
        app: nginx
    spec:
      containers:
      - name: nginx
        image: nginx:1.14.2
        ports:
        - containerPort: 80
  • This code is for my-policy.yml .
# This is original policy file from the kyverno docs
apiVersion: kyverno.io/v1
kind: ClusterPolicy
metadata:
  name: disallow-latest-tag
  annotations:
    policies.kyverno.io/title: Disallow Latest Tag
    policies.kyverno.io/category: Best Practices
    policies.kyverno.io/severity: medium
    policies.kyverno.io/subject: Pod
    policies.kyverno.io/description: >-
      The ':latest' tag is mutable and can lead to unexpected errors if the
      image changes. A best practice is to use an immutable tag that maps to
      a specific version of an application Pod. This policy validates that the image
      specifies a tag and that it is not called `latest`.      
spec:
  validationFailureAction: audit
  background: true
  rules:
  - name: require-image-tag
    match:
      resources:
        kinds:
        - Pod
    validate:
      message: "An image tag is required."
      pattern:
        spec:
          containers:
          - image: "*:*"
  - name: validate-image-tag
    match:
      resources:
        kinds:
        - Pod
    validate:
      message: "Using a mutable image tag e.g. 'latest' is not allowed."
      pattern:
        spec:
          containers:
          - image: "!*:latest"
  • Now edit the spec section of the configuration file in my-policy.yml as below.

      spec:
        validationFailureAction: enforce
        background: true
        failurePolicy: Fail
    
  • We are done with the edition, now let's try to see if Kyverno stops us if we are trying to deploy nginx:latest for this update nginx.yml so it looks as follows.

      apiVersion: apps/v1
      kind: Deployment
      metadata:
        name: nginx-deployment
        labels:
          app: nginx
      spec:
        replicas: 1
        selector:
          matchLabels:
            app: nginx
        template:
          metadata:
            labels:
              app: nginx
          spec:
            containers:
            - name: nginx
              image: nginx:latest
              ports:
              - containerPort: 80
    
  • Now apply the my-policy.yml using the following command.

      kubectl apply -f my-policy.yml
    
      clusterpolicy.kyverno.io/disallow-latest-tag created
    
  • Now apply the nginx.yml using the following command.

      kubectl apply -f nginx.yml
    
  • You should get an error message similar to.

      Error from server: error when creating "nginx.yml": admission webhook "validate.kyverno.svc-fail" denied the request: 
    
      policy Deployment/default/nginx-deployment for resource violation: 
    
      disallow-latest-tag:
        autogen-validate-image-tag: 'validation error: Using a mutable image tag e.g. ''latest''
          is not allowed. rule autogen-validate-image-tag failed at path /spec/template/spec/containers/0/image/'
    
  • you have successfully created a policy that doesn't allow :latest tags on the image.

  • Now change the tag in the nginx.yml file to :1.14.2 .

      image: nginx:1.14.2
    
  • and now lets try to apply the nginx.yml file again and this should get deployed as the image no longer has :latest tag.

      kubectl apply -f nginx.yml
    
      deployment.apps/nginx-deployment created
    

    That's it, that's how you implement the policies and control them with Kyverno. You can use several pre-existing policies or you can manually create your own too. And that is everything for this blog.

Resources

Thank you so much for reading 💙

Like | Follow | Subscribe to the Newsletter.

Catch me on my socials here: bio.link/yashpawar