Selecting Resources

Use match and exclude to filter and select resources.

The match and exclude filters control which resources policies are applied to.

The match and exclude clauses have the same structure and can each contain the following elements:

  • resources: select resources by names, namespaces, kinds, label selectors, annotations, and namespace selectors.
  • subjects: select users, user groups, and service accounts
  • roles: select namespaced roles
  • clusterRoles: select cluster wide roles

At least one element must be specified in a match.resources.kinds or exclude block. The kind attribute is mandatory when working with the resources element. Wildcards (*) are currently not supported in the match.resources.kinds field.

In addition, a user may specify the group and apiVersion with a kind in the match / exclude declarations for a policy rule.

Supported formats:

  • Group/Version/Kind
  • Version/Kind
  • Kind

To resolve kind naming conflicts, specify the API group and version. For example, the Kubernetes API, Calico, and Antrea all register a Kind with the name NetworkPolicy.

These can be distinguished as:

  • networking.k8s.io/v1/NetworkPolicy
  • crd.antrea.io/v1alpha1/NetworkPolicy

When Kyverno receives an admission controller request (i.e., a validation or mutation webhook), it first checks to see if the resource and user information matches or should be excluded from processing. If both checks pass, then the rule logic to mutate, validate, or generate resources is applied.

Match statements

In any rule statement, there must be a single match statement to function as the filter to which the rule will apply. Although the match statement can be complex having many different elements, there must be at least one. The most common type of element in a match statement is one which filters on categories of Kubernetes resources, for example Pods, Deployments, Services, Namespaces, etc. Variable substitution is not currently supported in match or exclude statements.

In this snippet, the match statement matches on all resources that have the kind Service. It does not take any other criteria into consideration, only that it be of kind Service.

1spec:
2  rules:
3  - name: no-LoadBalancer
4    match:
5      resources:
6        kinds:
7        - Service

By combining multiple elements in the match statement, you can be more selective as to which resources you wish to process. Additionally, wildcards are supported for even greater control. For example, by adding the resources.name field, the previous match statement can further filter out Services that begin with the text “prod-”.

1spec:
2  rules:
3  - name: no-LoadBalancer
4    match:
5      resources:
6        name: "prod-*"
7        kinds:
8        - Service

This will now match on only Services that begin with the name “prod-” but not those which begin with “dev-” or any other prefix. In both match and exclude statements, wildcards are supported to make selection more flexible.

In this snippet, the match statement matches only resources that have the group networking.k8s.io, version v1 and kind NetworkPolicy. By adding Group,Version,Kind in the match statement, you can be more selective as to which resources you wish to process.

1spec:
2  rules:
3  - name: no-LoadBalancer
4    match:
5      resources:
6        kinds:
7        - networking.k8s.io/v1/NetworkPolicy

By adding the only version and kind in the match statements, will filter out the kind only based on version.

1spec:
2  rules:
3  - name: no-LoadBalancer
4    match:
5      resources:
6        kinds:
7        - v1/NetworkPolicy

Here are some other examples of match statements.

Match a Deployment or StatefulSet with a specific label

This is an example that selects a Deployment OR a StatefulSet with a label app=critical.

Condition checks inside the resources block follow the logic “AND across types but an OR within list types”. For example, if a rule match contains a list of kinds and a list of namespaces, the rule will be evaluated if the request contains any one (OR) of the kinds AND any one (OR) of the namespaces. Conditions inside clusterRoles, roles, and subjects are always evaluated using a logical OR operation, as each request can only have a single instance of these values.

In the below snippet, kinds and selector are peer/sibling elements, and so they are ANDed together.

 1spec:
 2  rules:
 3    - name: match-critical-app
 4      match:
 5        # AND across kinds and namespaceSelector
 6        resources:
 7          # OR inside list of kinds
 8          kinds:
 9          - Deployment
10          - StatefulSet
11          selector:
12            matchLabels:
13              app: critical

This pattern can be leveraged to produce very fine-grained control over the selection of resources, for example the snippet as shown below which combines match elements that include resources, subjects, roles, and clusterRoles.

Advanced match statement

 1spec:
 2  # validationFailureAction controls admission control behaviors,
 3  # when a policy rule fails:
 4  # - use 'enforce' to block resource creation or modification
 5  # - use 'audit' to allow resource updates and report policy violations
 6  validationFailureAction: enforce
 7  # Each policy has a list of rules applied in declaration order
 8  rules:
 9    # Rules must have a unique name
10    - name: "check-pod-controller-labels"
11      # Each rule matches specific resource described by "match" field.
12      match:
13        resources:
14          kinds: # Required, list of kinds
15          - Deployment
16          - StatefulSet
17          # Optional resource name. Supports wildcards (* and ?)
18          name: "mongo*"
19          # Optional list of namespaces. Supports wildcards (* and ?)
20          namespaces:
21          - "dev*"
22          - test
23          # Optional label selectors. Values support wildcards (* and ?)
24          selector:
25              matchLabels:
26                  app: mongodb
27              matchExpressions:
28                  - {key: tier, operator: In, values: [database]}
29        # Optional users or service accounts to be matched
30        subjects:
31        - kind: User
32          name: mary@somecorp.com
33        # Optional roles to be matched
34        roles:
35        # Optional clusterroles to be matched
36        clusterRoles: 
37        - cluster-admin

Match Deployments in Namespaces using labels

This example selects Deployments in Namespaces that have a label type=connector or type=compute using a namespaceSelector.

Here, kinds and namespaceSelector are peer elements under match.resources and are evaluated using a logical AND operation.

 1spec:
 2  rules:
 3    - name: check-min-replicas
 4      match:
 5        # AND across resources and selector
 6        resources:
 7          # OR inside list of kinds
 8          kinds:
 9          - Deployment
10          namespaceSelector:
11            matchExpressions:
12              - key: type 
13                operator: In
14                values: 
15                - connector
16                - compute

Combining match and exclude

All match and exclude conditions must be satisfied for a resource to be selected for the policy rule. In other words, the match and exclude conditions are evaluated using a logical AND operation. Elements in the exclude block follow the same specifications as those in the match block.

Exclude cluster-admin ClusterRole

Here is an example of a rule that matches all Pods excluding those created by using the cluster-admin ClusterRole.

 1spec:
 2  rules:
 3    name: match-pods-except-cluster-admin
 4    match:
 5      resources:
 6        kinds:
 7        - Pod
 8    exclude:
 9      clusterRoles:
10      - cluster-admin

Exclude kube-system namespace

This rule matches all Pods except those in the kube-system Namespace.

 1spec:
 2  rules:
 3    name: match-pods-except-admin
 4    match:
 5      resources:
 6        kinds:
 7        - Pod
 8    exclude:
 9      resources:
10        namespaces:
11        - kube-system

Match a label and exclude users and roles

The following example matches all resources with label app=critical excluding the resources created by ClusterRole cluster-admin OR by the user John.

 1spec:
 2  rules:
 3    - name: match-criticals-except-given-rbac
 4      match:
 5        resources:
 6          kind:
 7          - Pod
 8          selector:
 9            matchLabels:
10              app: critical
11      exclude:
12        clusterRoles:
13        - cluster-admin
14        subjects:
15        - kind: User
16          name: John

Match all Pods using annotations

Here is an example of a rule that matches all Pods having imageregistry: "https://hub.docker.com/" annotations.

1spec:
2  rules:
3    - name: match-pod-annotations
4      match:
5        resources:
6          annotations:
7            imageregistry: "https://hub.docker.com/"
8          kinds:
9            - Pod
Last modified August 09, 2021 at 6:18 PM PST: fix "names" to "name" (4540423)