Skip to main content

Add a custom Gatekeeper rule

This page tells you how to add your own rule to OPA Gatekeeper, when the policy type is gatekeeper. In this example, the rule requires an owner label on each Deployment.

A Gatekeeper rule has two parts:

  • A ConstraintTemplate contains the logic of the rule, in the Rego language, and the parameters that the rule accepts. Gatekeeper creates a new resource kind for each ConstraintTemplate, for example K8sRequiredLabels.
  • A Constraint is a resource of this new kind. It tells Gatekeeper where to apply the rule, with which parameters, and what to do with a violation.

For more examples, see the Gatekeeper policy library. If the policy type is kyverno, write a Kyverno policy instead.

Write the rule​

Use a plugin to add the rule to the cluster. Create a directory for the plugin, for example plugins/policy-required-labels, next to furyctl.yaml, with these files.

  1. Write the ConstraintTemplate in template.yaml:

    plugins/policy-required-labels/template.yaml
    apiVersion: templates.gatekeeper.sh/v1
    kind: ConstraintTemplate
    metadata:
    name: k8srequiredlabels
    spec:
    crd:
    spec:
    names:
    kind: K8sRequiredLabels
    validation:
    openAPIV3Schema:
    type: object
    properties:
    labels:
    type: array
    items:
    type: string
    targets:
    - target: admission.k8s.gatekeeper.sh
    rego: |
    package k8srequiredlabels

    violation[{"msg": msg}] {
    provided := {label | input.review.object.metadata.labels[label]}
    required := {label | label := input.parameters.labels[_]}
    missing := required - provided
    count(missing) > 0
    msg := sprintf("%v '%v' does not have the labels: %v", [input.review.kind.kind, input.review.object.metadata.name, missing])
    }
  2. Write the Constraint in constraint.yaml:

    plugins/policy-required-labels/constraint.yaml
    apiVersion: constraints.gatekeeper.sh/v1beta1
    kind: K8sRequiredLabels
    metadata:
    name: deployment-must-have-owner
    spec:
    # Start with dryrun: Gatekeeper records the violations and blocks nothing
    enforcementAction: dryrun
    match:
    kinds:
    - apiGroups: ["apps"]
    kinds: ["Deployment"]
    # The namespaces of the SD modules
    excludedNamespaces:
    - kube-system
    - logging
    - monitoring
    - ingress-nginx
    - ingress-haproxy
    - cert-manager
    - tigera-operator
    - calico-system
    - calico-api
    - vmware-system-csi
    - pomerium
    - tracing
    - forecastle
    - external-dns
    - headlamp
    parameters:
    labels: ["owner"]
    warning

    Exclude the namespaces of the SD modules. A rule that blocks their resources can make the next furyctl apply fail. The list above is the list of the SD default rules.

  3. Write the placeholder for the resource kind in kapp-exists.yaml:

    plugins/policy-required-labels/kapp-exists.yaml
    # furyctl applies plugins with kapp. Gatekeeper creates this
    # CustomResourceDefinition after kapp applies the ConstraintTemplate.
    # The annotation tells kapp to wait for it and not to create it.
    apiVersion: apiextensions.k8s.io/v1
    kind: CustomResourceDefinition
    metadata:
    name: k8srequiredlabels.constraints.gatekeeper.sh
    annotations:
    kapp.k14s.io/exists: ""
    spec:
    group: constraints.gatekeeper.sh
    versions:
    - name: v1beta1
    names:
    kind: K8sRequiredLabels

    Without this file, kapp cannot apply the Constraint, because its resource kind does not exist yet. SD uses the same method for its default rules.

  4. Write the Kustomize file in kustomization.yaml:

    plugins/policy-required-labels/kustomization.yaml
    apiVersion: kustomize.config.k8s.io/v1beta1
    kind: Kustomization

    resources:
    - kapp-exists.yaml
    - template.yaml
    - constraint.yaml

Apply the rule​

  1. Add the plugin to furyctl.yaml:

    furyctl.yaml
    spec:
    plugins:
    kustomize:
    - name: policy-required-labels
    folder: ./plugins/policy-required-labels
  2. Apply the configuration:

    furyctl apply --phase plugins
  3. Make sure that Gatekeeper created the resource kind of the rule:

    kubectl get constrainttemplate k8srequiredlabels -o jsonpath='{.status.created}'

    The command prints true.

Find the violations​

The audit process of Gatekeeper examines the resources that already exist in the cluster, at regular intervals. To see the violations that it found, read the status of the Constraint:

kubectl get k8srequiredlabels deployment-must-have-owner -o yaml

The status.totalViolations field gives the number of violations, and the status.violations list gives the resources. The audit process records a maximum of 20 violations for each Constraint.

You can also see the violations in Gatekeeper Policy Manager, in the Constraints page.

Enforce the rule​

When the resources of the cluster obey the rule, change enforcementAction in constraint.yaml:

  • warn: the Kubernetes API accepts the resource, and kubectl shows a warning.
  • deny: the Kubernetes API rejects the resource.

Then apply the configuration again with furyctl apply --phase plugins.

To make sure that the rule blocks a resource, send a request to the Kubernetes API without a change to the cluster:

kubectl create deployment test --image=nginx:1.27 -n default --dry-run=server

With deny, the API rejects the request. The error message contains one line for each rule that the Deployment does not obey. The SD default rules also reject this Deployment, because it has no probes and no resource limits. The line of the new rule is:

[deployment-must-have-owner] Deployment 'test' does not have the labels: {"owner"}

Remove the rule​

Remove the plugin from furyctl.yaml, then delete it from the cluster with kapp. For more information, see Plugins › Uninstallation.

kapp delete -n kube-system -a kfd-plugin-policy-required-labels

When kapp deletes the ConstraintTemplate, Gatekeeper deletes the resource kind of the rule and the Constraint.