Basic Concepts
Policy Definition
Before creating a policy instance, you need to define a policy definition, which describes both the Rego that enforces the constraint and the schema of the constraint. The schema of a policy definition allows an admin to fine-tune the behavior of a constraint, much like arguments to a function. The Rego code in a policy definition describes the specific logic of enforcement and implements different compliance rules based on your requirements. Policy definitions are flexible. Admins can adjust policy behaviors based on actual requirements when creating policy instances to meet compliance control requirements in different scenarios. For more information, see the official documentation.
Here is an example of a policy definition that requires all labels described by the constraint to be present:
apiVersion: templates.gatekeeper.sh/v1 kind: ConstraintTemplate metadata: name: k8srequiredlabels spec: crd: spec: names: kind: K8sRequiredLabels validation: # Schema for the `parameters` field openAPIV3Schema: type: object properties: labels: type: array items: type: string targets: - target: admission.k8s.gatekeeper.sh rego: | package k8srequiredlabels violation[{"msg": msg, "details": {"missing_labels": missing}}] { provided := {label | input.review.object.metadata.labels[label]} required := {label | label := input.parameters.labels[_]} missing := required - provided count(missing) > 0 msg := sprintf("you must provide labels: %v", [missing]) }
Policy Instances
Policy instances are used to inform Gatekeeper that the admin wants a ConstraintTemplate to be enforced, and how. For more information, see the official documentation.
The following is an example of a policy instance that uses the previously mentioned K8sRequiredLabels policy definition to ensure that the Gatekeeper enforces the specified label on all namespaces:
apiVersion: constraints.gatekeeper.sh/v1beta1 kind: K8sRequiredLabels metadata: name: ns-must-have-gk spec: enforcementAction: deny match: kinds: - apiGroups: [""] kinds: ["Namespace"] parameters: labels: ["gatekeeper"]
In this example, the K8sRequiredLabels policy is used and the action for executing the policy is set to deny, which means that the Gatekeeper will deny requests that violate the policy. This policy is specified in match to apply only to namespace resources. In parameters, a label that must exist on the resource is specified. The example label is gatekeeper.
Feedback
Was this page helpful?
Provide feedbackThank you very much for your feedback. We will continue working to improve the documentation.See the reply and handling status in My Cloud VOC.
For any further questions, feel free to contact us through the chatbot.
Chatbot