[Yandex Cloud documentation](../../../index.md) > [Yandex Managed Service for Kubernetes](../../index.md) > [Tutorials](../index.md) > Using Cloud Marketplace products > Setting up Kyverno &amp; Kyverno Policies

# Setting up Kyverno & Kyverno Policies

[Kyverno](https://kyverno.io) and its extension, [kyverno-policies](https://github.com/kyverno/kyverno/tree/main/charts/kyverno-policies), help manage Kubernetes security policies which appear in Kyverno as Kubernetes resources.

To integrate [Kyverno & Kyverno Policies](https://yandex.cloud/en/marketplace/products/yc/kyverno) into Managed Service for Kubernetes:

1. [Install Kyverno & Kyverno Policies](#install-kyverno).
1. [Check how the policy works for the baseline profile](#check-baseline).
1. [Create and test your own Kyverno policy](#create-check-policies).

If you no longer need the resources you created, [delete them](#clear-out).


## Required paid resources {#paid-resources}

The support cost for this solution includes:

* Fee for using the master and outgoing traffic in a Managed Service for Kubernetes cluster (see [Managed Service for Kubernetes pricing](../../pricing.md)).
* Fee for using computing resources, OS, and storage in cluster nodes (VMs) (see [Compute Cloud pricing](../../../compute/pricing.md)).
* Fee for a public IP address assigned to cluster nodes (see [Virtual Private Cloud pricing](../../../vpc/pricing.md#prices-public-ip)).


## Getting started {#before-you-begin}

1. Create a Managed Service for Kubernetes [cluster](../../concepts/index.md#kubernetes-cluster) and [node group](../../concepts/index.md#node-group).

   {% list tabs group=instructions %}

   - Manually {#manual}

     1. If you do not have a [network](../../../vpc/concepts/network.md#network) yet, [create one](../../../vpc/operations/network-create.md).
     1. If you do not have any [subnets](../../../vpc/concepts/network.md#subnet) yet, [create them](../../../vpc/operations/subnet-create.md) in the [availability zones](../../../overview/concepts/geo-scope.md) where the new Kubernetes cluster and node group will reside.
     1. [Create security groups](../../operations/connect/security-groups.md) for the Managed Service for Kubernetes cluster and its node groups.

        {% note warning %}
        
        The configuration of security groups determines performance and availability of the cluster and the services and applications running in it.
        
        {% endnote %}

     1. [Create a Managed Service for Kubernetes cluster](../../operations/kubernetes-cluster/kubernetes-cluster-create.md) and [node group](../../operations/node-group/node-group-create.md) with any suitable configuration. When creating, specify the preconfigured security groups.

   - Terraform {#tf}

     1. If you do not have Terraform yet, [install it](../../../tutorials/infrastructure-management/terraform-quickstart.md#install-terraform).
     1. [Get the authentication credentials](../../../tutorials/infrastructure-management/terraform-quickstart.md#get-credentials). You can add them to environment variables or specify them later in the provider configuration file.
     1. [Configure and initialize a provider](../../../tutorials/infrastructure-management/terraform-quickstart.md#configure-provider). There is no need to create a provider configuration file manually, you can [download it](https://github.com/yandex-cloud-examples/yc-terraform-provider-settings/blob/main/provider.tf).
     1. Place the configuration file in a separate working directory and [specify the parameter values](../../../tutorials/infrastructure-management/terraform-quickstart.md#configure-provider). If you did not add the authentication credentials to environment variables, specify them in the configuration file.

     1. Download the [k8s-cluster.tf](https://github.com/yandex-cloud-examples/yc-mk8s-cluster-infrastructure/blob/main/k8s-cluster.tf) cluster configuration file to the same working directory. This file describes:
        * [Network](../../../vpc/concepts/network.md#network).
        * [Subnet](../../../vpc/concepts/network.md#subnet).
        * Managed Service for Kubernetes cluster.
        * [Service account](../../../iam/concepts/users/service-accounts.md) required for the Managed Service for Kubernetes cluster and node group.
        * [Security groups](../../../vpc/concepts/security-groups.md) which contain [rules](../../operations/connect/security-groups.md) required for the Managed Service for Kubernetes cluster and its node groups.

            {% note warning %}
            
            The configuration of security groups determines performance and availability of the cluster and the services and applications running in it.
            
            {% endnote %}

     1. Specify the following in the configuration file:
        * [Folder ID](../../../resource-manager/operations/folder/get-id.md).
        * [Kubernetes version](../../concepts/release-channels-and-updates.md) for the Managed Service for Kubernetes cluster and node groups.
        * Kubernetes cluster CIDR.
        * Service account name. It must be unique within the folder.
     1. Validate your Terraform configuration files using this command:

        ```bash
        terraform validate
        ```

        Terraform will display any configuration errors detected in your files.
     1. Create the required infrastructure:

        1. Run this command to view the planned changes:
        
           ```bash
           terraform plan
           ```
        
           If you described the configuration correctly, the terminal will display a list of the resources to update and their parameters. This is a verification step that does not apply changes to your resources.
        
        1. If everything looks correct, apply the changes:
           1. Run this command:
        
              ```bash
              terraform apply
              ```
        
           1. Confirm updating the resources.
           1. Wait for the operation to complete.

        All the required resources will be created in the specified folder. You can check resource availability and their settings in the [management console](https://console.yandex.cloud).

   {% endlist %}

1. [Install kubect](https://kubernetes.io/docs/tasks/tools/install-kubectl) and [configure it to work with the new cluster](../../operations/connect/index.md#kubectl-connect).

## Install Kyverno & Kyverno Policies {#install-kyverno}

Follow [this guide](https://yandex.cloud/en/marketplace/products/yc/kyverno) to install [Kyverno & Kyverno Policies](../../operations/applications/kyverno.md) with the following settings:

* **Pod Security Standard profile**: `baseline`.
* **Validation failure action**: `enforce`.

The `baseline` [Pod Security Standard profile](https://kubernetes.io/docs/concepts/security/pod-security-standards/) already contains a minimum restriction policy that prevents known privilege abuses.

## Check how the policy works for the baseline profile {#check-baseline}

* Create the `nginx` pod with standard settings:

  ```bash
  kubectl run nginx --image nginx
  ```

  Result:

  ```text
  pod/nginx created
  ```

  Such a pod satisfies the policy requirements for the `baseline` profile.

* Create the `nginx` pod in privileged mode:

  ```bash
  kubectl run nginx --image nginx --privileged=true
  ```

  Result:

  ```text
  Error from server: admission webhook "validate.kyverno.svc-fail" denied the request:

  policy Pod/default/nginx for resource violation:

  disallow-privileged-containers:
    privileged-containers: 'validation error: Privileged mode is disallowed. The fields
      spec.containers[*].securityContext.privileged and spec.initContainers[*].securityContext.privileged
      must be unset or set to `false`. rule privileged-containers failed at path /spec/containers/0/securityContext/privileged/'
  ```

  The policy rules for the `baseline` profile prohibit creating pods in privileged mode.

{% note info %}

Even though the policies target pods, Kyverno applies them to all resources that can create pods.

{% endnote %}

## Create and test your own Kyverno policy {#create-check-policies}

1. Create a policy that requires all [pods](../../concepts/index.md#pod) to have the `app.kubernetes.io/name` [label](../../../resource-manager/concepts/labels.md):
   1. Save the `ClusterPolicy` specification to a YAML file named `policy.yaml`:

      ```yaml
      apiVersion: kyverno.io/v1
      kind: ClusterPolicy
      metadata:
        name: require-labels
      spec:
        validationFailureAction: Enforce
        rules:
        - name: check-for-labels
          match:
            any:
            - resources:
                kinds:
                - Pod
          validate:
            message: "label 'app.kubernetes.io/name' is required"
            pattern:
              metadata:
                labels:
                  app.kubernetes.io/name: "?*"
      ```

   1. Run this command:

      ```bash
      kubectl apply -f policy.yaml
      ```

      Result:

      ```text
      clusterpolicy.kyverno.io/require-labels created
      ```

## Test Kyverno & Kyverno Policies {#check-apps}

* Create the `nginx` pod with no `app.kubernetes.io/name` Kubernetes label:

  ```bash
  kubectl run nginx --image nginx
  ```

  Result:
  ```text
  Error from server: admission webhook "validate.kyverno.svc-fail" denied the request:
  resource Pod/default/nginx was blocked due to the following policies

  require-labels:
    check-for-labels: 'validation error: label ''app.kubernetes.io/name'' is required.
      Rule check-for-labels failed at path /metadata/labels/app.kubernetes.io/name/'
  ```

* Create the `nginx` pod with the `app.kubernetes.io/name` label:

  ```bash
  kubectl run nginx --image nginx --labels app.kubernetes.io/name=nginx
  ```

  Result:

  ```text
  pod/nginx created
  ```

## Delete the resources you created {#clear-out}

Some resources are not free of charge. Delete the resources you no longer need to avoid paying for them:

{% list tabs group=instructions %}

- Manually {#manual}

  1. [Delete the Kubernetes cluster](../../operations/kubernetes-cluster/kubernetes-cluster-delete.md).
  1. [Delete the created subnets](../../../vpc/operations/subnet-delete.md) and [networks](../../../vpc/operations/network-delete.md).
  1. [Delete the created service account](../../../iam/operations/sa/delete.md).

- Terraform {#tf}

  1. In the terminal window, go to the directory containing the infrastructure plan.
  
      {% note warning %}
  
      Make sure the directory has no Terraform manifests with the resources you want to keep. Terraform deletes all resources that were created using the manifests in the current directory.
  
      {% endnote %}
  
  1. Delete resources:
  
      1. Run this command:
  
          ```bash
          terraform destroy
          ```
  
      1. Confirm deleting the resources and wait for the operation to complete.
  
      All the resources described in the Terraform manifests will be deleted.

{% endlist %}