Skip to content

Constraint Templates

Constraint Templates describes both the Rego that enforces the constraint and the schema of the constraint. The constraint schema allows an admin to fine-tune the behavior of a constraint, much like arguments to a function. For example, a Constraint Template can be created to check all the labels described in Constraints to be present. Templates are always defined in Yaml format where the user can create policy as a code


Create New Template

Perform the below steps to create a new constraint template:

  • Login to the Controller and select Constraint Templates under the OPA Gatekeeper. Users can view the list of existing templates on the Constraint Templates page
  • Click New Template
  • Provide a name for the template and select an Artifact Sync
  • To upload the files from the system, select Upload files manually from the Artifact Sync drop-down

Example of Yaml file:

apiVersion: templates.gatekeeper.sh/v1beta1
kind: ConstraintTemplate
metadata:
  name: k8srequiredlabels
spec:
  crd:
    spec:
      names:
        kind: K8sRequiredLabels
      validation:
        # Schema for the `parameters` field
        openAPIV3Schema:
          properties:
            labels:
              type: array
              items: 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])
        }
  • To use the files available from the git repository, select Pull files from repository from the Artifact Sync drop-down
  • Click Create to proceed or Cancel to abort the process

OPA New Template

  • Click Choose File and upload the Yaml file

Advanced Settings (Optional)

  • Click Advanced Settings to select any of the below options

  • force: Enabling force option forces resource updates through a replacement strategy

  • disableOpenAPIValidation: Enabling DisableOpenAPIValidation option prevents the Helm install action from validating rendered templates against the Kubernetes OpenAPI Schema

Below is an example of Upload files manually

Upload Yaml file

Below is an example of Pull files from Repository

Git Pull

  • Click Save & Exit

Edit / Delete Templates

  • Click the Delete icon to delete or Edit icon to edit the existing templates

Edit/Delete

Template Types

Two types of Constraint Templates are Custom and System

  • Templates created by customers are listed as Custom
  • Templates created by system for reference are listed as System. Users can edit but cannot delete the System templates