# Kubernetes - OPA Gatekeeper

{{#include ../../../banners/hacktricks-training.md}}

**The original author of this page is** [**Guillaume**](https://www.linkedin.com/in/guillaume-chapela-ab4b9a196)

## Definition

Open Policy Agent (OPA) Gatekeeper is a tool used to enforce admission policies in Kubernetes. These policies are defined using Rego, a policy language provided by OPA. Below is a basic example of a policy definition using OPA Gatekeeper:

```rego
package k8srequiredlabels

violation[{"msg": msg}] {
    provided := {label | input.review.object.metadata.labels[label]}
    required := {label | label := input.parameters.labels[label]}
    missing := required - provided
    count(missing) > 0
    msg := sprintf("Required labels missing: %v", [missing])
}

default allow = false
```

This Rego policy checks if certain labels are present on Kubernetes resources. If the required labels are missing, it returns a violation message. This policy can be used to ensure that all resources deployed in the cluster have specific labels.

## Apply Constraint

To use this policy with OPA Gatekeeper, you would define a **ConstraintTemplate** and a **Constraint** in Kubernetes:

```yaml
apiVersion: templates.gatekeeper.sh/v1beta1
kind: ConstraintTemplate
metadata:
  name: k8srequiredlabels
spec:
  crd:
    spec:
      names:
        kind: K8sRequiredLabels
  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[label]}
            missing := required - provided
            count(missing) > 0
            msg := sprintf("Required labels missing: %v", [missing])
        }

        default allow = false
```

```yaml
apiVersion: constraints.gatekeeper.sh/v1beta1
kind: K8sRequiredLabels
metadata:
  name: ensure-pod-has-label
spec:
  match:
    kinds:
      - apiGroups: [""]
        kinds: ["Pod"]
  parameters:
    labels:
      requiredLabel1: "true"
      requiredLabel2: "true"
```

In this YAML example, we define a **ConstraintTemplate** to require labels. Then, we name this constraint `ensure-pod-has-label`, which references the `k8srequiredlabels` ConstraintTemplate and specifies the required labels.

When Gatekeeper is deployed in the Kubernetes cluster, it will enforce this policy, preventing the creation of pods that do not have the specified labels.

## References

* [https://github.com/open-policy-agent/gatekeeper](https://github.com/open-policy-agent/gatekeeper)



{{#include ../../../banners/hacktricks-training.md}}
