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.
-
Write the ConstraintTemplate in
template.yaml:plugins/policy-required-labels/template.yamlapiVersion: templates.gatekeeper.sh/v1kind: ConstraintTemplatemetadata:name: k8srequiredlabelsspec:crd:spec:names:kind: K8sRequiredLabelsvalidation:openAPIV3Schema:type: objectproperties:labels:type: arrayitems:type: stringtargets:- target: admission.k8s.gatekeeper.shrego: |package k8srequiredlabelsviolation[{"msg": msg}] {provided := {label | input.review.object.metadata.labels[label]}required := {label | label := input.parameters.labels[_]}missing := required - providedcount(missing) > 0msg := sprintf("%v '%v' does not have the labels: %v", [input.review.kind.kind, input.review.object.metadata.name, missing])} -
Write the Constraint in
constraint.yaml:plugins/policy-required-labels/constraint.yamlapiVersion: constraints.gatekeeper.sh/v1beta1kind: K8sRequiredLabelsmetadata:name: deployment-must-have-ownerspec:# Start with dryrun: Gatekeeper records the violations and blocks nothingenforcementAction: dryrunmatch:kinds:- apiGroups: ["apps"]kinds: ["Deployment"]# The namespaces of the SD modulesexcludedNamespaces:- kube-system- logging- monitoring- ingress-nginx- ingress-haproxy- cert-manager- tigera-operator- calico-system- calico-api- vmware-system-csi- pomerium- tracing- forecastle- external-dns- headlampparameters:labels: ["owner"]warningExclude the namespaces of the SD modules. A rule that blocks their resources can make the next
furyctl applyfail. The list above is the list of the SD default rules. -
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/v1kind: CustomResourceDefinitionmetadata:name: k8srequiredlabels.constraints.gatekeeper.shannotations:kapp.k14s.io/exists: ""spec:group: constraints.gatekeeper.shversions:- name: v1beta1names:kind: K8sRequiredLabelsWithout this file, kapp cannot apply the Constraint, because its resource kind does not exist yet. SD uses the same method for its default rules.
-
Write the Kustomize file in
kustomization.yaml:plugins/policy-required-labels/kustomization.yamlapiVersion: kustomize.config.k8s.io/v1beta1kind: Kustomizationresources:- kapp-exists.yaml- template.yaml- constraint.yaml
Apply the rule
-
Add the plugin to
furyctl.yaml:furyctl.yamlspec:plugins:kustomize:- name: policy-required-labelsfolder: ./plugins/policy-required-labels -
Apply the configuration:
furyctl apply --phase plugins -
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, andkubectlshows 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.