<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Mariam Fahmy on Medium]]></title>
        <description><![CDATA[Stories by Mariam Fahmy on Medium]]></description>
        <link>https://medium.com/@mariamfahmy66?source=rss-1fe19812a5f8------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>Stories by Mariam Fahmy on Medium</title>
            <link>https://medium.com/@mariamfahmy66?source=rss-1fe19812a5f8------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 05:51:43 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@mariamfahmy66/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Validating Admission Policies in Kyverno]]></title>
            <link>https://medium.com/@mariamfahmy66/validating-admission-policies-in-kyverno-1f4a3e972f92?source=rss-1fe19812a5f8------2</link>
            <guid isPermaLink="false">https://medium.com/p/1f4a3e972f92</guid>
            <category><![CDATA[policy-as-code]]></category>
            <category><![CDATA[kyverno]]></category>
            <category><![CDATA[kubernetes]]></category>
            <dc:creator><![CDATA[Mariam Fahmy]]></dc:creator>
            <pubDate>Tue, 30 May 2023 17:31:38 GMT</pubDate>
            <atom:updated>2023-05-31T11:49:19.225Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/320/1*R3cXB6SVWft1rkBS1Fwcqw.png" /></figure><p><a href="https://github.com/kyverno">Kyverno</a>, in simple terms, is a policy engine for <a href="https://kubernetes.io/">Kubernetes</a> that can be used to describe policies and validate resource requests against those policies. It allows us to create <em>Policies</em> for our Kubernetes cluster on different levels. It enables us to validate, change, and create resources based on the policies we define.</p><p>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.<br>A Policy consists of different clauses such as:</p><ul><li>Match: It selects resources that match the given criteria.</li><li>Exclude: It selects all but excludes resources that match the specified criteria.</li></ul><blockquote>Match and Exclude are used to select resources, users, user groups, service accounts, namespaced roles, and cluster-wide roles.</blockquote><ul><li>Validate: It validates the properties of the new resource and it is created if it matches what is declared in the rule.</li><li>Mutate: It modifies matching resources.</li><li>Generate: It creates additional resources.</li><li>Verify Images: It verifies container image signatures using <a href="https://github.com/sigstore/cosign">Cosign</a>.</li></ul><blockquote>Each rule can contain only a single validate, mutate, generate, or verifyImages child declaration.</blockquote><p>In this blog article, I’m going to show how to use validate rules, and how to use CEL expressions for resource validation.</p><h3>Motivation</h3><p>Let’s start with creating a Kyverno policy that ensures no hostPath volumes are in use for the newly created pods.</p><pre>kubectl apply -f - &lt;&lt;EOF<br>apiVersion: kyverno.io/v1<br>kind: ClusterPolicy<br>metadata:<br>  name: disallow-host-path<br>spec:<br>  validationFailureAction: Enforce<br>  background: false<br>  rules:<br>    - name: host-path<br>      match:<br>        any:<br>        - resources:<br>            kinds:<br>              - Deployment<br>      validate:<br>        message: &gt;-<br>                    HostPath volumes are forbidden. The field spec.template.spec.volumes[*].hostPath must be unset.<br>        pattern:<br>          spec:<br>            template:<br>              spec:<br>                =(volumes):<br>                  - X(hostPath): &quot;null&quot;<br>EOF</pre><p>spec.rules.pattern is used to define fields and expressions that must be matched by the new resources to pass the validation rule.</p><pre>pattern:<br>  spec:<br>     =(volumes):<br>       - X(hostPath): &quot;null&quot;</pre><p>This is read as “if spec.volumesis defined, then spec.volumes.hostPath shouldn’t be defined”. The new pods must match what’s defined in the pattern to be successfully created.</p><p>Now, let’s try to deploy an app that uses a hostPath:</p><pre>kubectl apply -f - &lt;&lt;EOF<br>apiVersion: apps/v1<br>kind: Deployment<br>metadata:<br>  name: nginx<br>spec:<br>  replicas: 2<br>  selector:<br>    matchLabels:<br>      app: nginx<br>  template:<br>    metadata:<br>      labels:<br>        app: nginx<br>    spec:<br>      containers:<br>      - name: nginx-server<br>        image: nginx<br>        volumeMounts:<br>          - name: udev<br>            mountPath: /data<br>      volumes:<br>      - name: udev<br>        hostPath:<br>          path: /etc/udev<br>EOF</pre><p>We can see that our policy is enforced, great!</p><pre>Error from server: error when creating &quot;STDIN&quot;: admission webhook &quot;validate.kyverno.svc-fail&quot; denied the request: <br><br>resource Deployment/default/nginx was blocked due to the following policies <br><br>disallow-host-path:<br>  host-path: &#39;validation error: HostPath volumes are forbidden. The field spec.template.spec.volumes[*].hostPath<br>    must be unset. rule host-path failed at path /spec/template/spec/volumes/0/hostPath/&#39;</pre><p>An alternative way is to use <a href="https://github.com/google/cel-spec">Common Expression Language (CEL)</a> expressions to validate resources.</p><p>CEL was first introduced to Kubernetes for the Validation rules for CustomResourceDefinitions and then it was used by <a href="https://kubernetes.io/blog/2022/12/20/validating-admission-policies-alpha/">Kubernetes Validating Admission Policies</a> in 1.26.</p><p>As a mentee in the LFX mentorship program, I had the opportunity to work on supporting Validating Admission Policies in Kyverno, which is currently in the development phase and scheduled for release in v1.11.</p><p>With CEL expressions you can do the following:</p><ul><li>Define policies that take into account multiple fields and values in a resource, and make decisions based on the outcome of those conditions.</li><li>Use logical operators, comparison operators, and custom functions to create policies that are easier to read and understand.</li><li>Define your own custom functions and operators, which can be used to customize the behavior of your policies.</li></ul><p>It’s worth considering the strengths and weaknesses of both patterns and CEL expressions and choosing the approach that best suits your needs.</p><h3>CEL Expressions for Validations in Kyverno</h3><p>we’ll start with creating a simple policy that uses CEL expressions to validate resources. Then, we’ll create a policy that uses CEL preconditions for fine-grained request filtering. Finally, we’ll create a policy that uses parameter resources.</p><h4>Create a simple policy to disallow host paths for Deployments</h4><p>The below policy ensures no hostPath volumes are in use for deployments.</p><pre>kubectl apply -f - &lt;&lt;EOF<br>apiVersion: kyverno.io/v1<br>kind: ClusterPolicy<br>metadata:<br>  name: disallow-host-path<br>spec:<br>  validationFailureAction: Enforce<br>  background: false<br>  rules:<br>    - name: host-path<br>      match:<br>        any:<br>        - resources:<br>            kinds:<br>              - Deployment<br>      validate:<br>        cel:<br>          expressions:<br>            - expression: &quot;!has(object.spec.template.spec.volumes) || object.spec.template.spec.volumes.all(volume, !has(volume.hostPath))&quot;<br>              message: &quot;HostPath volumes are forbidden. The field spec.template.spec.volumes[*].hostPath must be unset.&quot;<br>EOF</pre><p>spec.rules.validate.cel contains CEL expressions which use the <a href="https://github.com/google/cel-spec">Common Expression Language (CEL)</a> to validate the request. If an expression evaluates to false, the validation check is enforced according to the spec.validationFailureActionfield.</p><p>If we tried to deploy an app that uses a hostPath, the resource creation will be blocked as it violates the rule. It’s the same behaviour we saw before.</p><h4>CEL Preconditions in Kyverno Policies</h4><p>The below policy ensures the hostPort field is set to a value between 5000 and 6000 for pods whose metadata.name set tonginx</p><pre>kubectl apply -f - &lt;&lt;EOF<br>apiVersion: kyverno.io/v1<br>kind: ClusterPolicy<br>metadata:<br>  name: disallow-host-port-range<br>spec:<br>  validationFailureAction: Enforce<br>  background: false<br>  rules:<br>    - name: host-port-range<br>      match:<br>        any:<br>        - resources:<br>            kinds:<br>              - Pod<br>      celPreconditions:<br>          - name: &quot;first match condition in CEL&quot;<br>            expression: &quot;object.metadata.name.matches(&#39;nginx&#39;)&quot;<br>      validate:<br>        cel:<br>          expressions:<br>          - expression: &quot;object.spec.containers.all(container, !has(container.ports) || container.ports.all(port, !has(port.hostPort) || (port.hostPort &gt;= 5000 &amp;&amp; port.hostPort &lt;= 6000)))&quot;<br>            message: &quot;The only permitted hostPorts are in the range 5000-6000.&quot;<br>EOF</pre><p>spec.rules.celPreconditions are <a href="https://kubernetes.io/docs/reference/using-api/cel/">CEL expressions</a>. All celPreconditions must evaluate to true for the resource to be evaluated. Therefore, any pods that has nginx in its metadata.name will be evaluated.</p><p>Now, let’s try to deploy an apache server that contains hostPortset to 80.</p><pre>kubectl apply -f - &lt;&lt;EOF<br>apiVersion: v1<br>kind: Pod<br>metadata:<br>  name: apache<br>spec:<br>  containers:<br>  - name: apache-server<br>    image: httpd<br>    ports:<br>    - containerPort: 8080<br>      hostPort: 80<br>EOF</pre><p>You’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 excatly what we need.</p><pre>pod/apache created</pre><p>Now, let’s try to deploy an nginx server that contains hostPortset to 80.</p><pre>kubectl apply -f - &lt;&lt;EOF<br>apiVersion: v1<br>kind: Pod<br>metadata:<br>  name: nginx<br>spec:<br>  containers:<br>  - name: nginx-server<br>    image: nginx<br>    ports:<br>    - containerPort: 8080<br>      hostPort: 80<br>EOF</pre><p>Since the new pod satisfies the celPreconditions, therefore the validation rule will be applied on it. As a result, the creation of the pod will be blocked as it violates the rule.</p><pre>Error from server: error when creating &quot;STDIN&quot;: admission webhook &quot;validate.kyverno.svc-fail&quot; denied the request: <br><br>resource Pod/default/nginx was blocked due to the following policies <br><br>disallow-host-port-range:<br>  host-port-range: The only permitted hostPorts are in the range 5000-6000.</pre><h4>Parameter Resources in Kyverno Policies</h4><p>The below policy ensures the deployment replicas is less than a specific value. This value is defined in a paramter resource.</p><pre>kubectl apply -f - &lt;&lt;EOF<br>apiVersion: kyverno.io/v1<br>kind: ClusterPolicy<br>metadata:<br>  name: check-deployment-replicas<br>spec:<br>  validationFailureAction: Enforce<br>  background: false<br>  rules:<br>    - name: deployment-replicas<br>      match:<br>        any:<br>        - resources:<br>            kinds:<br>              - Deployment<br>      validate:<br>        cel:<br>          paramKind: <br>            apiVersion: rules.example.com/v1<br>            kind: ReplicaLimit<br>          paramRef:<br>            name: &quot;replica-limit-test.example.com&quot;<br>          expressions:<br>            - expression: &quot;object.spec.replicas &lt;= params.maxReplicas&quot;<br>              messageExpression:  &quot;&#39;Deployment spec.replicas must be less than &#39; + string(params.maxReplicas)&quot;<br>EOF</pre><p>The cel.paramKind and cel.paramRefspecifies the kind of resources used to parameterize this policy. For this example, it is configured by ReplicaLimitcustom resources.</p><p>The ReplicaLimitcould be as follows:</p><pre>kubectl apply -f - &lt;&lt;EOF<br>apiVersion: rules.example.com/v1<br>kind: ReplicaLimit<br>metadata:<br>  name: &quot;replica-limit-test.example.com&quot;<br>maxReplicas: 3<br>EOF</pre><p>Now, let’s try to deploy an app with 5 replicas.</p><pre>kubectl apply -f - &lt;&lt;EOF<br>apiVersion: apps/v1<br>kind: Deployment<br>metadata:<br>  name: nginx<br>spec:<br>  replicas: 5<br>  selector:<br>    matchLabels:<br>      app: nginx<br>  template:<br>    metadata:<br>      labels:<br>        app: nginx<br>    spec:<br>      containers:<br>      - name: nginx-server<br>        image: nginx<br>EOF</pre><p>As we expect, the deployment creation will be blocked because it violates the rule.</p><pre>Error from server: error when creating &quot;STDIN&quot;: admission webhook &quot;validate.kyverno.svc-fail&quot; denied the request: <br><br>resource Deployment/default/nginx was blocked due to the following policies <br><br>check-deployment-replicas:<br>  deployment-replicas: Deployment spec.replicas must be less than 3</pre><p>Now, let’s try to deploy an app with 2 replicas.</p><pre>kubectl apply -f - &lt;&lt;EOF<br>apiVersion: apps/v1<br>kind: Deployment<br>metadata:<br>  name: nginx<br>spec:<br>  replicas: 2<br>  selector:<br>    matchLabels:<br>      app: nginx<br>  template:<br>    metadata:<br>      labels:<br>        app: nginx<br>    spec:<br>      containers:<br>      - name: nginx-server<br>        image: nginx<br>EOF</pre><p>The deployment is created successfully, Great!</p><pre>deployment.apps/nginx created</pre><h3>Validating Admission Policies using Kyverno CLI</h3><p>The <a href="https://kyverno.io/docs/kyverno-cli/">Kyverno Command Line Interface (CLI)</a> is designed to validate and test policy behavior to resources prior to adding them to a cluster.</p><p>One of the Kyverno CLI commands are apply and test commands.</p><ul><li>The apply command is used to perform a dry run on one or more policies for the given manifest(s).</li><li>The test command is used to test a given set of resources against one or more policies to check the desired results.</li></ul><p>Kyverno CLI now can be used to apply/test <a href="https://kubernetes.io/docs/reference/access-authn-authz/validating-admission-policy/">Kubernetes Validating Admission Policies</a> that were introduced in 1.26</p><h4>Validating Admission Policies using Kyverno apply</h4><p>Here’s a Validating Admission Policy:</p><pre>cat &gt; check-deployment-replicas.yaml<br>apiVersion: admissionregistration.k8s.io/v1alpha1<br>kind: ValidatingAdmissionPolicy<br>metadata:<br>  name: check-deployments-replicas<br>spec:<br>  failurePolicy: Fail<br>  matchConstraints:<br>    resourceRules:<br>    - apiGroups:   [&quot;apps&quot;]<br>      apiVersions: [&quot;v1&quot;]<br>      operations:  [&quot;CREATE&quot;, &quot;UPDATE&quot;]<br>      resources:   [&quot;deployments&quot;]<br>  validations:<br>    - expression: &quot;object.spec.replicas &lt;= 2&quot;<br>      message: &quot;Replicas must be less than or equal 2&quot;</pre><p>A deployment can be:</p><pre>cat &gt; deployment.yaml<br>apiVersion: apps/v1<br>kind: Deployment<br>metadata:<br>  name: nginx<br>spec:<br>  replicas: 2<br>  selector:<br>    matchLabels:<br>      app: nginx<br>  template:<br>    metadata:<br>      labels:<br>        app: nginx<br>    spec:<br>      containers:<br>      - name: nginx-server<br>        image: nginx</pre><p>Let’s apply the policy on the resource using kyverno apply as follows:</p><pre>kyverno apply ./check-deployment-replicas.yaml --resource=deployment.yaml<br><br>pass: 1, fail: 0, warn: 0, error: 0, skip: 0 </pre><p>In case we changed the replicas to 3, you’ll see that there’s a failed policy.</p><pre>kyverno apply ./check-deployment-replicas.yaml --resource=deployment.yaml<br><br>pass: 0, fail: 1, warn: 0, error: 0, skip: 0</pre><h4>Validating Admission Policies using Kyverno test</h4><p>Lets’ try to test two deployments aganist the above validating admission policy and check the desired results.</p><pre>cat &gt; deployment.yaml<br>apiVersion: apps/v1<br>kind: Deployment<br>metadata:<br>  name: nginx-deployment-1<br>  labels:<br>    app: nginx-1<br>spec:<br>  replicas: 2<br>  selector:<br>    matchLabels:<br>      app: nginx-1<br>  template:<br>    metadata:<br>      labels:<br>        app: nginx-1<br>    spec:<br>      containers:<br>      - name: nginx<br>        image: nginx:1.14.2<br>        ports:<br>        - containerPort: 80<br>---<br>apiVersion: apps/v1<br>kind: Deployment<br>metadata:<br>  name: nginx-deployment-2<br>  labels:<br>    app: nginx-2<br>spec:<br>  replicas: 4<br>  selector:<br>    matchLabels:<br>      app: nginx-2<br>  template:<br>    metadata:<br>      labels:<br>        app: nginx-2<br>    spec:<br>      containers:<br>      - name: nginx<br>        image: nginx:1.14.2<br>        ports:<br>        - containerPort: 80</pre><p>The tests are written in a file name kyverno-test.yaml so we will create two tests, one for each deployment and test them aganist the policy.</p><pre>cat &gt; kyverno-test.yaml<br>name: check-deployment-replicas-test<br>policies:<br>  - check-deployment-replicas.yaml<br>resources:<br>  - deployment.yaml<br>results:<br>  - policy: check-deployment-replicas<br>    isVap: true<br>    resource: nginx-deployment-1<br>    kind: Deployment<br>    result: pass<br>  - policy: check-deployment-replicas<br>    isVap: true<br>    resource: nginx-deployment-2<br>    kind: Deployment<br>    result: fail</pre><p>Now, we’re ready to test the two deployments aganist validating admission policy. A directory test-dir is created and it contains the above manifests:</p><ol><li>check-deployment-replicas.yaml</li><li>deployment.yaml</li><li>kyverno-test.yaml</li></ol><pre>kyverno test ./test-dir/<br><br>Executing check-deployment-replicas-test...<br><br>│────│───────────────────────────│──────│────────────────────────────────│────────│<br>│ ID │ POLICY                    │ RULE │ RESOURCE                       │ RESULT │<br>│────│───────────────────────────│──────│────────────────────────────────│────────│<br>│  1 │ check-deployment-replicas │      │ /Deployment/nginx-deployment-1 │ Pass   │<br>│  2 │ check-deployment-replicas │      │ /Deployment/nginx-deployment-2 │ Pass   │<br>│────│───────────────────────────│──────│────────────────────────────────│────────│<br><br>Test Summary: 2 tests passed and 0 tests failed</pre><p>As expected, the two tests passed because the actual result of each test matches the desired result as defined in the test manifest.</p><h3>Conclusion</h3><p>This blog post highlights the use of CEL expressions in Kyverno validation rules as well as the use of Kyverno CLI apply/test commands for Kubernetes Validating Admission policies.</p><p>Visit <a href="https://kyverno.io/">kyverno.io</a> to explore more!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1f4a3e972f92" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>