Table of Contents

OPA Gatekeeper

OPA Gatekeeper - A policy enforcement tool for Kubernetes that leverages policy as code to ensure compliance with security standards. https://github.com/open-policy-agent/gatekeeper

OPA Gatekeeper is a powerful and customizable admission webhook for Kubernetes that leverages the Open Policy Agent (OPA) to enforce policies and strengthen governance within your Kubernetes clusters. It allows you to define and manage policies as code, ensuring compliance and security across your Kubernetes resources.

Key Features

Benefits

Code Examples

1. **ConstraintTemplate Definition:**

```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 := {key ]] | [[ input.review.object.metadata.labels[key]}
         required := {key ]] | [[ key := input.parameters.labels[_]}
         missing := required - provided
         count(missing) > 0
         msg := sprintf("you must provide labels: %v", [missing])
       }
```

This ConstraintTemplate defines a policy that requires specific labels to be present on Kubernetes resources.

2. **Constraint Definition:**

```yaml apiVersion: constraints.gatekeeper.sh/v1beta1 kind: K8sRequiredLabels metadata:

 name: require-labels-on-namespace
spec:
 match:
   kinds:
     - apiGroups: [""]
       kinds: ["Namespace"]
 parameters:
   labels: ["environment"]
```

This Constraint enforces the “k8srequiredlabels” policy, requiring the “environment” label to be present on all Namespace resources.

Additional Resources