KOP Recipes - Use OPA Gatekeeper - Rafay Product Documentation

What Will You Do

In this exercise, you will be defining policies and viewing violations against configured policies.


Assumptions


Policy for Pod Security Standards (PSS)

Important

For more information on Pod Security Standards (PSS), please refer here

Kyverno's implementation of Pod Security Standards (PSS) is available as a helm chart and we will leverage this chart for this exercise.

Policy to check for labels against a namespace

This example policy is to ensure that namespaces are being created with appropriate labels in a cluster.

apiVersion: kyverno.io/v1
kind: ClusterPolicy
metadata:
  name: k8srequiredlabels
spec:
  validationFailureAction: audit
  background: true
  rules:
  - name: check-for-labels
    match:
      resources:
        kinds:
        - Namespace
    validate:
      message: "The label `appteam.kubernetes.io/name` is required."
      pattern:
        metadata:
          labels:
            appteam.kubernetes.io/name: "?*"

The above examples set the validation failure action to audit. Insecure or non-compliant configurations can be blocked by setting the validationFailureAction to enforce.

Background scanning, enabled by default in a Policy or ClusterPolicy object with the spec.background field, allows Kyverno to scan existing resources and find if they match any validate rules. If existing resources are found which would violate an existing policy, the background scan notes them in a ClusterPolicyReport or a PolicyReport object, depending on if the resource is namespaced or not. It does not block any existing resources that match a validate rule, even in enforce mode. Background scanning is an optional field and defaults to true, only taking effect on validate rules.

More examples for Kyverno policies are available here


Checking for violations against configured policies

Policy reports, like Kyverno policies, have both Namespaced and cluster-scoped variants; a PolicyReport is a Namespaced resource while a ClusterPolicyReport is a cluster-scoped resource. A ClusterPolicy (a cluster-scoped policy) contains a rule which matches on Pods (a Namespaced resource). Results generated from this policy and rule are written to a PolicyReport in the Namespace where the Pod exists.

You can view a summary of the Namespaced policy reports using the following command:

kubectl get policyreport -A

Policy reports can be inspected using kubectl describe or kubectl get.

kubectl describe polr <name> -n <namespace>
kubectl get polr <name> -n <namespace> -o yaml

Similarly, you can view the cluster-wide report using:

kubectl get clusterpolicyreport

Recap

Congratulations! You have deployed Kyverno policies and viewed violations against resources in the cluster successfully.