Search

Chapter 3. Gatekeeper operator

download PDF

Gatekeeper is a validating webhook with auditing capabilities that can enforce custom resource definition-based policies that are run with the Open Policy Agent (OPA). You can install Gatekeeper on your cluster by using the Gatekeeper operator policy. Gatekeeper constraints can be used to evaluate Kubernetes resource compliance. You can leverage OPA as the policy engine, and use Rego as the policy language.

Prerequisite: A Red Hat Advanced Cluster Management for Kubernetes or Red Hat OpenShift Container Platform Plus subscription is required to install Gatekeeper and apply Gatekeeper policies to your cluster. Gatekeeper is supported only on OpenShift Container Platform versions, except version 3.11, supported by the latest version of Red Hat Advanced Cluster Management.

Continue reading to learn more about using the Gatekeeper operator:

3.1. Integrating Gatekeeper constraints and constraint templates

Gatekeeper policies are written by using constraint templates (ConstraintTemplates) and constraints. View the following YAML examples that use Gatekeeper constraints in Red Hat Advanced Cluster Management policies:

  • ConstraintTemplates and constraints: Use the Gatekeeper integration feature by using Red Hat Advanced Cluster Management policies for multicluster distribution of Gatekeeper constraints and Gatekeeper audit results aggregation on the hub cluster. The following example defines a Gatekeeper ConstraintTemplate and constraint (K8sRequiredLabels) to ensure the gatekeeper label is set on all namespaces:

    apiVersion: policy.open-cluster-management.io/v1
    kind: Policy
    metadata:
      name: require-gatekeeper-labels-on-ns
    spec:
      remediationAction: inform 1
      disabled: false
      policy-templates:
        - objectDefinition:
            apiVersion: templates.gatekeeper.sh/v1beta1
            kind: ConstraintTemplate
            metadata:
              name: k8srequiredlabels
              annotations:
                policy.open-cluster-management.io/severity: low 2
            spec:
              crd:
                spec:
                  names:
                    kind: K8sRequiredLabels
                  validation:
                    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])
                    }
        - objectDefinition:
            apiVersion: constraints.gatekeeper.sh/v1beta1
            kind: K8sRequiredLabels
            metadata:
              name: ns-must-have-gk
              annotations:
                policy.open-cluster-management.io/severity: low 3
            spec:
              enforcementAction: dryrun
              match:
                kinds:
                  - apiGroups: [""]
                    kinds: ["Namespace"]
              parameters:
                labels: ["gatekeeper"]
    1
    Since the remediationAction is set to inform, the enforcementAction field of the Gatekeeper constraint is overridden to warn. This means that Gatekeeper detects and warns you about creating or updating a namespace that is missing the gatekeeper label. If the policy remediationAction is set to enforce, the Gatekeeper constraint enforcementAction field is overridden to deny. In this context, this configuration prevents any user from creating or updating a namespace that is missing the gatekeeper label.
    2 3
    Optional: Set a severity value for the policy.open-cluster-management.io/severity annotation for each Gatekeeper constraint or constraint template. Valid values are the same as for other Red Hat Advanced Cluster Management policy types: low, medium, high, or critical.

    With the previous policy, you might receive the following policy status message: warn - you must provide labels: {"gatekeeper"} (on Namespace default); warn - you must provide labels: {"gatekeeper"} (on Namespace gatekeeper-system). Once a policy containing Gatekeeper constraints or ConstraintTemplates is deleted, the constraints and ConstraintTemplates are also deleted from the managed cluster.

    To view the Gatekeeper audit results for a specific managed cluster from the console, navigate to the policy template Results page. If search is enabled, view the YAML of the Kubernetes objects that failed the audit.

    Notes:

    • The Related resources section is only available when the audit results are generated by Gatekeeper version 3.9 or newer.
    • The Gatekeeper audit functionality runs every minute by default. Audit results are sent back to the hub cluster to be viewed in the Red Hat Advanced Cluster Management policy status of the managed cluster.
  • policy-gatekeeper-admission: Use the policy-gatekeeper-admission configuration policy within a Red Hat Advanced Cluster Management policy to check for Kubernetes API requests denied by the gatekeeper admission webhook:

    apiVersion: policy.open-cluster-management.io/v1
    kind: ConfigurationPolicy
    metadata:
      name: policy-gatekeeper-admission
    spec:
      remediationAction: inform # will be overridden by remediationAction in parent policy
      severity: low
      object-templates:
        - complianceType: mustnothave
          objectDefinition:
            apiVersion: v1
            kind: Event
            metadata:
              namespace: openshift-gatekeeper-system # set it to the actual namespace where gatekeeper is running if different
              annotations:
                constraint_action: deny
                constraint_kind: K8sRequiredLabels
                constraint_name: ns-must-have-gk
                event_type: violation

3.1.1. Additional resources

3.2. Managing Gatekeeper operator policies

Use the Gatekeeper operator policy to install the Gatekeeper operator and Gatekeeper on a managed cluster. Learn to create, view, and update your Gatekeeper operator policies in the following sections.

Required access: Cluster administrator

3.2.1. Installing Gatekeeper using a Gatekeeper operator policy

Use the governance framework to install the Gatekeeper operator. Gatekeeper operator is available in the OpenShift Container Platform catalog. See Adding Operators to a cluster in the OpenShift Container Platform documentation for more information.

Use the configuration policy controller to install the Gatekeeper operator policy. During the install, the operator group and subscription pull the Gatekeeper operator to install it in your managed cluster. Then, the Gatekeeper operator creates a Gatekeeper custom resource to configure Gatekeeper. View the Gatekeeper operator custom resource sample.

Gatekeeper operator policy is monitored by the Red Hat Advanced Cluster Management configuration policy controller, where enforce remediation action is supported. Gatekeeper operator policies are created automatically by the controller when set to enforce.

3.2.2. Creating a Gatekeeper policy from the console

See the following procedure to create the policy from the console:

  1. Install the Gatekeeper policy by creating a policy from the console. Alternatively, you can navigate to the Additional resources section for a reference to the sample YAML to deploy policy-gatekeeper-operator.yaml.
  2. After you log in to your cluster, navigate to the Governance page.
  3. Select Create policy.
  4. As you complete the form, select Gatekeeper Operator from the Specifications field. The parameter values for your policy are automatically populated and the policy is set to inform by default.
  5. Set your remediation action to enforce to install Gatekeeper.

Note: Default values are generated by the operator.

3.2.2.1. Gatekeeper operator custom resource

apiVersion: operator.gatekeeper.sh/v1alpha1
kind: Gatekeeper
metadata:
  name: gatekeeper
spec:
  audit:
    replicas: 1
      auditEventsInvolvedNamespace: Enabled 1
    logLevel: DEBUG
    auditInterval: 10s
    constraintViolationLimit: 55
    auditFromCache: Enabled
    auditChunkSize: 66
    emitAuditEvents: Enabled
    resources:
      limits:
        cpu: 500m
        memory: 150Mi
      requests:
        cpu: 500m
        memory: 130Mi
  validatingWebhook: Enabled
  mutatingWebhook: Enabled
  webhook:
    replicas: 3
    emitAdmissionEvents: Enabled
    admissionEventsInvolvedNamespace: Enabled 2
    disabledBuiltins: - http.send
    operations: 3
     - "CREATE"
     - "UPDATE"
     - "CONNECT"
    failurePolicy: Fail
    resources:
      limits:
        cpu: 480m
        memory: 140Mi
      requests:
        cpu: 400m
        memory: 120Mi
  nodeSelector:
    region: "EMEA"
  affinity:
    podAffinity:
      requiredDuringSchedulingIgnoredDuringExecution:
        - labelSelector:
            matchLabels:
              auditKey: "auditValue"
          topologyKey: topology.kubernetes.io/zone
  tolerations:
    - key: "Example"
      operator: "Exists"
      effect: "NoSchedule"
  podAnnotations:
    some-annotation: "this is a test"
    other-annotation: "another test"
1
Enable the auditEventsInvolvedNamespace parameter to manage which namespace audit event to create. As a result, the following argument is added to the Gatekeeper controller deployment, --audit-events-involved-namespace: true.
2
Enable the admissionEventsInvolvedNamespace parameter to manage which namespace admission event to create. As a result, the following argument is added to the Gatekeeper controller deployment, --admission-events-involved-namespace: true.
3
You can use the following values to manage your webhook operations. Use the following values for the operations parameter, "CREATE", "UPDATE", "CONNECT", and "DELETE".

3.2.2.2. Configuring auditFromCache for sync details

The Gatekeeper operator exposes a setting in the custom resource definition within the auditFromCache audit, which is disabled by default. If you enable auditFromCache, then you need to set config.gatekeeper.sh for the sync details. See Configuring Audit in the Gatekeeper documentation.

The Gatekeeper operator collects resources from constraints that users install and then inserts those resources into the config resource. If resources do not exist, the operator creates config resources.

  1. Set auditFromCache to Automatic in the Gatekeeper resource, as displayed in the following example:

    apiVersion: operator.gatekeeper.sh/v1alpha1
    kind: Gatekeeper
    metadata:
      name: gatekeeper
    spec:
      audit: replicas: 2
        logLevel: DEBUG
        auditFromCache: Automatic

    See that the Gatekeeper operator adds syncOnlys parameter section to the config file in the following example:

    apiVersion: config.gatekeeper.sh/v1alpha1
    kind: Config
    metadata:
     name: config
     namespace: "openshift-gatekeeper-system"
    spec:
     sync:
       syncOnly:
       - group: ""
         version: "v1"
         kind: "Namespace"
       - group: ""
         version: "v1"
         kind: "Pod"
  2. Get the explanation of the sync setting, run the following command from your terminal:

    oc explain gatekeeper.spec.audit.auditFromCache

3.2.3. Upgrading Gatekeeper and the Gatekeeper operator

You can upgrade the versions for Gatekeeper and the Gatekeeper operator. When you install the Gatekeeper operator with the Gatekeeper operator policy, notice the value for upgradeApproval. The operator upgrades automatically when upgradeApproval is set to Automatic.

You must approve the upgrade of the Gatekeeper operator manually for each cluster when upgradeApproval is set to Manual.

3.2.4. Updating Gatekeeper operator policy

Learn to update the Gatekeeper operator policy by viewing the following section.

3.2.4.1. Viewing Gatekeeper operator policy from the console

View your Gatekeeper operator policy and the status from the console.

After you log in to your cluster from the console, click Governance to view a table list of your policies. Note: You can filter the table list of your policies by selecting the Policies tab or Cluster violations tab.

Select the policy-gatekeeper-operator policy to view more details. View the policy violations by selecting the Clusters tab.

3.2.4.2. Disabling Gatekeeper operator policy

Disable your gatekeeper operator policy.

After you log in to your Red Hat Advanced Cluster Management for Kubernetes console, navigate to the Governance page to view a table list of your policies.

Select the Actions icon for the policy-gatekeeper-operator policy, then click Disable. The Disable Policy dialog box appears.

Click Disable policy. Your policy-gatekeeper-operator policy is disabled.

3.2.5. Deleting Gatekeeper operator policy

Delete the Gatekeeper operator policy from the CLI or the console.

  • Delete Gatekeeper operator policy from the CLI:

    1. Delete Gatekeeper operator policy by running the following command:

      oc delete policies.policy.open-cluster-management.io <policy-gatekeeper-operator-name> -n <namespace>

      After your policy is deleted, it is removed from your target cluster or clusters.

    2. Verify that your policy is removed by running the following command:

      oc get policies.policy.open-cluster-management.io <policy-gatekeeper-operator-name> -n <namespace>
  • Delete Gatekeeper operator policy from the console:

    Navigate to the Governance page to view a table list of your policies.

    Similar to the previous console instructions, click the Actions icon for the policy-gatekeeper-operator policy. Click Remove to delete the policy. From the Remove policy dialog box, click Remove policy.

Your Gatekeeper operator policy is deleted.

3.2.6. Uninstalling Gatekeeper policy, Gatekeeper, and Gatekeeper operator policy

Complete the following steps to uninstall Gatekeeper policy, Gatekeeper, and Gatekeeper operator policy:

  1. Remove the Gatekeeper Constraint and ConstraintTemplate that is applied on your managed cluster:

    1. Edit your Gatekeeper operator policy. Locate the ConfigurationPolicy template that you used to create the Gatekeeper Constraint and ConstraintTemplate.
    2. Change the value for complianceType of the ConfigurationPolicy template to mustnothave.
    3. Save and apply the policy.
  2. Remove Gatekeeper instance from your managed cluster:

    1. Edit your Gatekeeper operator policy. Locate the ConfigurationPolicy template that you used to create the Gatekeeper custom resource.
    2. Change the value for complianceType of the ConfigurationPolicy template to mustnothave.
  3. Remove the Gatekeeper operator that is on your managed cluster:

    1. Edit your Gatekeeper operator policy. Locate the ConfigurationPolicy template that you used to create the Subscription CR.
    2. Change the value for complianceType of the ConfigurationPolicy template to mustnothave.

Gatekeeper policy, Gatekeeper, and Gatekeeper operator policy are uninstalled.

3.2.7. Additional resources

Red Hat logoGithubRedditYoutubeTwitter

Learn

Try, buy, & sell

Communities

About Red Hat Documentation

We help Red Hat users innovate and achieve their goals with our products and services with content they can trust.

Making open source more inclusive

Red Hat is committed to replacing problematic language in our code, documentation, and web properties. For more details, see the Red Hat Blog.

About Red Hat

We deliver hardened solutions that make it easier for enterprises to work across platforms and environments, from the core datacenter to the network edge.

© 2024 Red Hat, Inc.