Using CEL Expressions in Kyverno Policies
Kyverno, in simple terms, is a policy engine for Kubernetes that can be used to describe policies and validate resource requests against those policies. It allows us to create policies for our Kubernetes cluster on different levels. It enables us to validate, change, and create resources based on our defined policies.
A Kyverno policy is a collection of rules. Whenever we receive an API request to our Kubernetes cluster, we validate it with a set of rules.
A policy consists of different clauses, such as:
- Match: It selects the resources to be included in a rule.
- Exclude: It selects a subset of the resources from the match block which should be excluded from a rule.
Match and Exclude are used to select resources, users, user groups, service accounts, namespaced roles, and cluster-wide roles.
- Validate: It validates the properties of the new resource, and it is created if it matches what is declared in the rule.
- Mutate: It modifies matching resources.
- Generate: It creates additional resources.
- Verify Images: It verifies container image signatures using Cosign and Notary.
Refer to Selecting Resources for more information.
Each rule can contain only a single validate, mutate, generate, or verifyImages child declaration.
In this post, I will show you how to write CEL expressions in Kyverno policies for resource validation. Common Expression Language (CEL) was first introduced to Kubernetes for the validation rules for CustomResourceDefinitions, and then it was used by Kubernetes ValidatingAdmissionPolicies in 1.26.
CEL Expressions in validate rules
Section titled “CEL Expressions in validate rules”Creating a policy to disallow host paths for Deployments
Section titled “Creating a policy to disallow host paths for Deployments”The below policy ensures no hostPath volumes are in use for Deployments.
kubectl apply -f - <<EOFapiVersion: kyverno.io/v1kind: ClusterPolicymetadata: name: disallow-host-pathspec: validationFailureAction: Enforce background: false rules: - name: host-path match: any: - resources: kinds: - Deployment validate: cel: expressions: - expression: "!has(object.spec.template.spec.volumes) || object.spec.template.spec.volumes.all(volume, !has(volume.hostPath))" message: "HostPath volumes are forbidden. The field spec.template.spec.volumes[*].hostPath must be unset."EOFspec.rules.validate.cel contains CEL expressions that use the Common Expression Language (CEL) to validate the request. If an expression evaluates to false, the validation check is enforced according to the spec.validationFailureAction field.
Now, let’s try deploying an app that uses a hostPath:
kubectl apply -f - <<EOFapiVersion: apps/v1kind: Deploymentmetadata: name: nginxspec: replicas: 2 selector: matchLabels: app: nginx template: metadata: labels: app: nginx spec: containers: - name: nginx-server image: nginx volumeMounts: - name: udev mountPath: /data volumes: - name: udev hostPath: path: /etc/udevEOFWe can see that our policy is enforced. Great!
Error from server: error when creating "STDIN": admission webhook "validate.kyverno.svc-fail" denied the request:
resource Deployment/default/nginx was blocked due to the following policies
disallow-host-path: host-path: HostPath volumes are forbidden. The field spec.template.spec.volumes[*].hostPath must be unset.Creating a policy to check StatefulSet Namespaces
Section titled “Creating a policy to check StatefulSet Namespaces”The below policy ensures that any StatefulSet is created in the production Namespace
kubectl apply -f - <<EOFapiVersion: kyverno.io/v1kind: ClusterPolicymetadata: name: check-statefulset-namespacespec: validationFailureAction: Enforce background: false rules: - name: statefulset-namespace match: any: - resources: kinds: - StatefulSet validate: cel: expressions: - expression: "namespaceObject.metadata.name == 'production'" message: "The StatefulSet must be created in the 'production' namespace."EOFLet’s try creating a StatefulSet in the default Namespace.
kubectl apply -f - <<EOFapiVersion: apps/v1kind: StatefulSetmetadata: name: bad-statefulsetspec: replicas: 1 selector: matchLabels: app: app template: metadata: labels: app: app spec: containers: - name: container2 image: nginxEOFAs expected, the Statefulset creation is blocked because it violates the rule
Error from server: error when creating "STDIN": admission webhook "validate.kyverno.svc-fail" denied the request:
resource StatefulSet/default/bad-statefulset was blocked due to the following policies
check-statefulset-namespace: statefulset-namespace: The StatefulSet must be created in the 'production' namespace.Let’s create a Statefulset in the production Namespace.
kubectl apply -f - << EOFapiVersion: apps/v1kind: StatefulSetmetadata: name: good-statefulset namespace: productionspec: replicas: 1 selector: matchLabels: app: app template: metadata: labels: app: app spec: containers: - name: container2 image: nginxEOFThe StatefulSet is successfully created. Great!
statefulset.apps/good-statefulset createdIn the previous two examples, we have used object in CEL expressions which refers to the incoming object and namespaceObject which refers to the Namespace that the incoming object belongs to.
Some other useful variables that we can use in CEL expressions are
- oldObject: The existing object. The value is null for CREATE requests.
- authorizer: It can be used to perform authorization checks.
- authorizer.requestResource: A shortcut for an authorization check configured with the request resource (group, resource, (subresource), namespace, name).
CEL Preconditions in Kyverno Policies
Section titled “CEL Preconditions in Kyverno Policies”The below policy ensures the hostPort field is set to a value between 5000 and 6000 for pods whose metadata.name set to nginx
kubectl apply -f - <<EOFapiVersion: kyverno.io/v1kind: ClusterPolicymetadata: name: disallow-host-port-rangespec: validationFailureAction: Enforce background: false rules: - name: host-port-range match: any: - resources: kinds: - Pod celPreconditions: - name: "first match condition in CEL" expression: "object.metadata.name.matches('nginx')" validate: cel: expressions: - expression: "object.spec.containers.all(container, !has(container.ports) || container.ports.all(port, !has(port.hostPort) || (port.hostPort >= 5000 && port.hostPort <= 6000)))" message: "The only permitted hostPorts are in the range 5000-6000."EOFspec.rules.celPreconditions are CEL expressions. All celPreconditions must be evaluated to true for the resource to be evaluated. Therefore, any Pod with nginx in its metadata.name will be evaluated.
Let’s try deploying an Apache server with hostPort set to 80.
kubectl apply -f - <<EOFapiVersion: v1kind: Podmetadata: name: apachespec: containers: - name: apache-server image: httpd ports: - containerPort: 8080 hostPort: 80EOFYou’ll see that it’s successfully created because the validation rule wasn’t applied on the new Pod as it doesn’t satisfy the celPreconditions. That’s exactly what we need.
Pod/apache createdLet’s try deploying an Nginx server with hostPort set to 80.
kubectl apply -f - <<EOFapiVersion: v1kind: Podmetadata: name: nginxspec: containers: - name: nginx-server image: nginx ports: - containerPort: 8080 hostPort: 80EOFSince the new Pod satisfies the celPreconditions, the validation rule will be applied. As a result, the creation of the Pod will be blocked as it violates the rule.
Error from server: error when creating "STDIN": admission webhook "validate.kyverno.svc-fail" denied the request:
resource Pod/default/nginx was blocked due to the following policies
disallow-host-port-range: host-port-range: The only permitted hostPorts are in the range 5000-6000.Parameter Resources in Kyverno Policies
Section titled “Parameter Resources in Kyverno Policies”The below policy ensures the deployment replicas are less than a specific value. This value is defined in a parameter resource.
kubectl apply -f - <<EOFapiVersion: kyverno.io/v1kind: ClusterPolicymetadata: name: check-deployment-replicasspec: validationFailureAction: Enforce background: false rules: - name: deployment-replicas match: any: - resources: kinds: - Deployment validate: cel: paramKind: apiVersion: rules.example.com/v1 kind: ReplicaLimit paramRef: name: "replica-limit-test.example.com" parameterNotFoundAction: "Deny" expressions: - expression: "object.spec.replicas <= params.maxReplicas" messageExpression: "'Deployment spec.replicas must be less than ' + string(params.maxReplicas)"EOFThe cel.paramKind and cel.paramRef specify the resource used to parameterize this policy. For this example, it is configured by ReplicaLimit custom resources.
The ReplicaLimit could be as follows:
kubectl apply -f - <<EOFapiVersion: rules.example.com/v1kind: ReplicaLimitmetadata: name: "replica-limit-test.example.com"maxReplicas: 3EOFHere’s the corresponding custom resource definition:
kubectl apply -f - <<EOFapiVersion: apiextensions.k8s.io/v1kind: CustomResourceDefinitionmetadata: name: replicalimits.rules.example.comspec: group: rules.example.com names: kind: ReplicaLimit plural: replicalimits scope: Namespaced versions: - name: v1 served: true storage: true schema: openAPIV3Schema: type: object properties: apiVersion: type: string kind: type: string metadata: type: object maxReplicas: type: integerEOFNow, let’s try deploying an app with five replicas.
kubectl apply -f - <<EOFapiVersion: apps/v1kind: Deploymentmetadata: name: nginxspec: replicas: 5 selector: matchLabels: app: nginx template: metadata: labels: app: nginx spec: containers: - name: nginx-server image: nginxEOFAs expected, the deployment creation will be blocked because it violates the rule.
Error from server: error when creating "STDIN": admission webhook "validate.kyverno.svc-fail" denied the request:
resource Deployment/default/nginx was blocked due to the following policies
check-deployment-replicas: deployment-replicas: Deployment spec.replicas must be less than 3Let’s try deploying an app with two replicas.
kubectl apply -f - <<EOFapiVersion: apps/v1kind: Deploymentmetadata: name: nginxspec: replicas: 2 selector: matchLabels: app: nginx template: metadata: labels: app: nginx spec: containers: - name: nginx-server image: nginxEOFThe deployment is created successfully. Great!
deployment.apps/nginx createdCEL Variables in Kyverno Policies
Section titled “CEL Variables in Kyverno Policies”If an expression grows too complicated, or part of the expression is reusable and computationally expensive to evaluate, We can extract some parts of the expressions into variables. A variable is a named expression that can be referred later as variables in other expressions.
The order of variables is important because a variable can refer to other variables defined before it. This ordering prevents circular references.
The below policy enforces that image repo names match the environment defined in its Namespace. It enforces that all containers of deployment have the image repo match the environment label of its Namespace except for “exempt” deployments or any containers that do not belong to the “example.com” organization (e.g., common sidecars). For example, if the Namespace has a label of {“environment”: “staging”}, all container images must be either staging.example.com/* or do not contain “example.com” at all, unless the deployment has {“exempt”: “true”} label.
kubectl apply -f - <<EOFapiVersion: kyverno.io/v1kind: ClusterPolicymetadata: name: image-matches-namespace-environment.policy.example.comspec: validationFailureAction: Enforce background: false rules: - name: image-matches-namespace-environment match: any: - resources: kinds: - Deployment validate: cel: variables: - name: environment expression: "'environment' in namespaceObject.metadata.labels ? namespaceObject.metadata.labels['environment'] : 'prod'" - name: exempt expression: "has(object.metadata.labels) && 'exempt' in object.metadata.labels && object.metadata.labels['exempt'] == 'true'" - name: containers expression: "object.spec.template.spec.containers" - name: containersToCheck expression: "variables.containers.filter(c, c.image.contains('example.com/'))" expressions: - expression: "variables.exempt || variables.containersToCheck.all(c, c.image.startsWith(variables.environment + '.'))" messageExpression: "'only ' + variables.environment + ' images are allowed in namespace ' + namespaceObject.metadata.name"EOFLet’s start with creating a Namespace that has a label of environment: staging
kubectl apply -f - <<EOFapiVersion: v1kind: Namespacemetadata: name: staging-ns labels: environment: stagingEOFAnd then create a deployment whose image is example.com/nginx in the staging-ns Namespace.
kubectl apply -f - <<EOFapiVersion: apps/v1kind: Deploymentmetadata: name: deployment-fail namespace: staging-nsspec: replicas: 1 selector: matchLabels: app: app template: metadata: labels: app: app spec: containers: - name: container2 image: example.com/nginxEOFAs expected, the deployment creation will be blocked since its image must be staging.example.com/nginx
Let’s try setting the deployment image to staging.example.com/nginx instead
kubectl apply -f - <<EOFapiVersion: apps/v1kind: Deploymentmetadata: name: deployment-pass namespace: staging-nsspec: replicas: 1 selector: matchLabels: app: app template: metadata: labels: app: app spec: containers: - name: container2 image: staging.example.com/nginxEOFThe deployment is created successfully. Great!
deployment.apps/deployment-pass createdAuto-Gen Rules for CEL Expressions
Section titled “Auto-Gen Rules for CEL Expressions”Since Kubernetes has many higher-level controllers that directly or indirectly manage Pods: Deployment, DaemonSet, StatefulSet, Job, and CronJob resources, it’d be inefficient to write a policy that targets Pods and every higher-level controller. Kyverno solves this issue by supporting the automatic generation of policy rules for higher-level controllers from a rule written exclusively for a Pod.
Check the autogen rules for more information.
For example, when creating a validation policy like below, which disallows latest image tags, the policy applies to all resources capable of generating Pods.
kubectl apply -f - <<EOFapiVersion: kyverno.io/v1kind: ClusterPolicymetadata: name: disallow-latest-tagspec: validationFailureAction: Enforce rules: - name: disallow-latest-tag match: any: - resources: kinds: - Pod validate: cel: expressions: - expression: "object.spec.containers.all(container, !container.image.contains('latest'))" message: "Using a mutable image tag e.g. 'latest' is not allowed."EOFOnce the policy is created, these other resources can be shown in auto-generated rules which Kyverno adds to the policy under the status object.
status: autogen: rules: - exclude: resources: {} generate: clone: {} cloneList: {} match: any: - resources: kinds: - DaemonSet - Deployment - Job - StatefulSet - ReplicaSet - ReplicationController resources: {} mutate: {} name: autogen-disallow-latest-tag validate: cel: expressions: - expression: object.spec.template.spec.containers.all(container, !container.image.contains('latest')) message: Using a mutable image tag e.g. 'latest' is not allowed. - exclude: resources: {} generate: clone: {} cloneList: {} match: any: - resources: kinds: - CronJob resources: {} mutate: {} name: autogen-cronjob-disallow-latest-tag validate: cel: expressions: - expression: object.spec.jobTemplate.spec.template.spec.containers.all(container, !container.image.contains('latest')) message: Using a mutable image tag e.g. 'latest' is not allowed.Let’s try creating an nginx deployment with the latest tag.
kubectl apply -f - << EOFapiVersion: apps/v1kind: Deploymentmetadata: name: nginx-deployment labels: app: nginxspec: replicas: 3 selector: matchLabels: app: nginx template: metadata: labels: app: nginx spec: containers: - name: nginx image: nginx:latestEOFAs expected the deployment creation is blocked.
Error from server: error when creating "STDIN": admission webhook "validate.kyverno.svc-fail" denied the request:
resource Deployment/default/nginx-deployment was blocked due to the following policies
disallow-latest-tag: autogen-disallow-latest-tag: Using a mutable image tag e.g. 'latest' is not allowed.Conclusion
Section titled “Conclusion”This blog post explains how to use CEL expressions in Kyverno policies to validate resources covering all the features introduced in Kubernetes ValidatingAdmissionPolicies. Stay tuned for our next post, where we’ll show you how to generate Kubernetes ValidatingAdmissionPolicies from Kyverno policies.