[Kyverno] Quick Start Guides

“This post is a Korean translation and summary of the Quick Start content from the official Kyverno documentation, intended to aid understanding.”

>

https://kyverno.io/blog/2023/11/16/kyverno-1.11-released/

Introduction to Kyverno Policies and Rule Types

This section provides a guide to quickly install and run Kyverno, and to demonstrate some of Kyverno’s core features. Guides focusing on Validation, Mutation, and Generation are available, allowing you to choose the item most suitable for your use case.

Note: These guides are designed for Proof of Concept (PoC) or hands-on practice and are not recommended for production environments. For detailed information on production environment installation, please refer to the [Installation Page].

First, install Kyverno using the latest release manifest.

kubectl create -f https://github.com/kyverno/kyverno/releases/latest/download/install.yaml

Next, choose the quick start guide you are interested in. Alternatively, you can proceed in order from the top.


1. Validate Resources

In the validation guide, we’ll look at a simple policy example that ensures all Pods must include a label called “team”. Validation is the most common use case for policies, acting as a decision-making process that determines “yes” or “no”. Resources that comply with the policy are allowed to pass (“yes, allowed”), while non-compliant resources may be denied passage (“no, not allowed”).

Another effect of validation policies is the generation of

Policy Reports

. Policy Reports are Custom Resources (CRDs) created and managed by Kyverno, which display the policy decision results for allowed resources in a user-friendly manner.

Add the policy below to your cluster. It contains a single validation rule requiring all Pods to have a “team” label. (Kyverno supports various rule types in addition to validation, such as mutation, generation, cleanup, and image verification.) The failureAction field is set to Enforce, which blocks non-compliant Pods. Using the default value of Audit would only report violations without blocking requests.

YAML

kubectl create -f- << EOF
apiVersion: kyverno.io/v1
kind: ClusterPolicy
metadata:
  name: require-labels
spec:
  # Create a rule named check-team that performs a check when a Pod-related match occurs
  rules:
  - name: check-team
    match:
      any:
      - resources:
          kinds:
          - Pod
    # The label named team must be configured. It cannot be absent.
    validate:
      failureAction: Enforce
      message: "label 'team' is required"
      pattern:
        metadata:
          labels:
            team: "?*"
EOF

Try creating a Deployment without the required label.

kubectl create deployment nginx --image=nginx

You should encounter an error like this:

error: failed to create deployment: admission webhook "validate.kyverno.svc-fail" denied the request: 
resource Deployment/default/nginx was blocked due to the following policies:
require-labels:
  autogen-check-team: 'validation error: label ''team'' is
    required. Rule autogen-check-team failed at path /spec/template/metadata/labels/team/'

In addition to returning an error, Kyverno generates an Event containing this information in the same namespace.

Note: Kyverno may be configured to exclude system namespaces like kube-system or kyverno. Please use a custom namespace or the default namespace for testing.

Note that the policy targets Pods, but the Deployment you just created was blocked. This is thanks to Kyverno’s rule auto-generation feature. Kyverno intelligently applies policies written specifically for Pods to all standard Kubernetes Pod controllers, including Deployments.

Now, try creating a Pod with the required label.

kubectl run nginx --image nginx --labels team=backend

This Pod configuration complies with the policy, so its creation is allowed. After the Pod is created, wait a few seconds and then check other actions performed by Kyverno. Run the following command to view the Policy Report Kyverno just generated.

kubectl get policyreport -o wide

You can see a Policy Report with a result of 1 in the “PASS” column. This is because the Pod you just created passed the policy.

NAME                                   KIND         NAME                            PASS   FAIL   WARN   ERROR   SKIP   AGE
3f9d6279-445b-403d-a255-2a0a8da419a8   Pod          nginx                           1      0      0      0       0      4s
72a484fd-29a8-4126-ade6-ade1c4aba275   ReplicaSet   my-backstage-84ff474f85         0      1      0      0       0      2m7s
7492fb75-0003-4d6d-9ce0-fcf52c933f0c   Pod          my-backstage-84ff474f85-8777r   0      1      0      0       0      2m7s
757ae125-e628-46b7-ab20-6849a831baae   Deployment   my-backstage                    0      1      0      0       0      2m7s

Delete the policy you just created to clean up.

kubectl delete clusterpolicy require-labels

Congratulations! You have successfully implemented a validation policy in your Kubernetes cluster.


2. Mutate Resources

Mutation is the ability to change or “transform” resources before they are admitted into the cluster. Mutation rules, similar to validation rules, select resources (such as Pods or ConfigMaps) and define their desired state.

Add the mutation policy below to your cluster. This policy adds a “team” label to all new Pods and sets its value to “bravo”, but only if the Pod does not already have this label assigned. The +(team) notation uses a Kyverno anchor to define the action to take when the label key is absent.

kubectl create -f- << EOF
apiVersion: kyverno.io/v1
kind: ClusterPolicy
metadata:
  name: add-labels
spec:
  # Perform the operation when the kind matches a Pod, similar to the previous rule
  rules:
  - name: add-team
    match:
      any:
      - resources:
          kinds:
          - Pod
    # This time, perform a mutation that merges the information team: bravo into the labels
    mutate:
      patchStrategicMerge:
        metadata:
          labels:
            +(team): bravo
EOF

Now, try creating a new Pod without the label defined.

kubectl run redis --image redis

Check the labels of the created Pod.

# kubectl get pod redis --show-labels
NAME    READY   STATUS              RESTARTS   AGE   LABELS
redis   0/1     ContainerCreating   0          7s    run=redis,team=bravo

You can see that the team=bravo label has been added by Kyverno. Now, try creating a Pod that already has the “team” label defined.

kubectl run newredis --image redis -l team=alpha

If you check the labels of this Pod again, you’ll see that Kyverno did not overwrite the value defined in the policy because the label already existed. As such, the merge functionality does not overwrite existing labels.

# kubectl get pod --show-labels newredis
NAME       READY   STATUS    RESTARTS   AGE   LABELS
newredis   1/1     Running   0          44s   team=alpha​

After completing the task, delete the policy.

kubectl delete clusterpolicy add-labels

3. Generate Resources

Kyverno has the ability to generate new Kubernetes resources based on definitions stored in policies. The generation feature is very powerful and flexible, offering not only initial creation but also the ability to continuously synchronize generated resources.

In this guide, we will look at a policy that automatically generates an image pull secret when a new namespace is created. First, create a test secret that mimics a real secret.

kubectl -n default create secret docker-registry regcred 
  --docker-server=myinternalreg.corp.com 
  --docker-username=john.doe 
  --docker-password=Passw0rd123! 
  --docker-email=john.doe@corp.com

By default, Kyverno is configured with minimal privileges and cannot access sensitive resources like secrets. You must grant permissions through cluster role aggregation.

kubectl apply -f- << EOF
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
  name: kyverno:secrets:view
  labels:
    rbac.kyverno.io/aggregate-to-admission-controller: "true"
    rbac.kyverno.io/aggregate-to-reports-controller: "true"
    rbac.kyverno.io/aggregate-to-background-controller: "true"
rules:
- apiGroups:
  - ''
  resources:
  - secrets
  verbs:
  - get
  - list
  - watch
---
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
  name: kyverno:secrets:manage
  labels:
    rbac.kyverno.io/aggregate-to-background-controller: "true"
rules:
- apiGroups:
  - ''
  resources:
  - secrets
  verbs:
  - create
  - update
  - delete
EOF

Now, create the following Kyverno policy. The sync-secrets policy detects newly created namespaces and replicates the secret you just created into that namespace.

kubectl create -f- << EOF
apiVersion: kyverno.io/v1
kind: ClusterPolicy
metadata:
  name: sync-secrets
spec:
  # This time, it operates when Namespace creation is detected
  rules:
  - name: sync-image-pull-secret
    match:
      any:
      - resources:
          kinds:
          - Namespace
    # A rule is included to create the Secret in the requested NS, and this is replicated from default
    generate:
      apiVersion: v1
      kind: Secret
      name: regcred
      namespace: "{{request.object.metadata.name}}"
      synchronize: true
      clone:
        namespace: default
        name: regcred
EOF

Create a new namespace for testing.

kubectl create ns mytestns

Check if the regcred secret exists in the new namespace.

kubectl -n mytestns get secret

You can see that Kyverno created the regcred secret using the source secret from the default namespace as a template. If you modify the original secret, Kyverno will synchronize the changes everywhere it was generated.

Finally, delete the policy to clean up.

kubectl delete clusterpolicy sync-secrets

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *