Kubernetes offers a flexible and scalable platform for deploying applications, but enforcing security, compliance, and governance policies across a cluster can be challenging. Open Policy Agent (OPA) addresses this challenge by enabling policy-as-code enforcement within Kubernetes.
In this blog, we’ll explore how to use OPA and the Gatekeeper project to define, enforce, and manage policies across a Kubernetes cluster in a structured way.
Open Policy Agent (OPA) is a powerful tool for defining and enforcing policies using a declarative approach. It allows users to create rules and conditions that determine whether specific operations should be permitted.
In a Kubernetes environment, OPA helps enforce best practices by ensuring that Pods meet security and compliance requirements—such as having the correct labels, using a safe security context, and avoiding direct host port bindings.
Designed for seamless integration with various systems, OPA processes JSON input, such as Kubernetes manifests, evaluates them against predefined policies, and returns a decision on whether they comply with the established rules.
OPA policies are written in Rego, a specialized query language designed to express complex conditions in a readable format. Instead of defining step-by-step execution logic, Rego allows you to specify what should be enforced—such as restricting specific configurations or flagging missing fields—while OPA handles the evaluation process. This declarative approach simplifies policy management, making it easier to maintain security, governance, and compliance across a Kubernetes cluster.
1. Add helm repository in Kubernetes cluster
Run the following commands to add the Gatekeeper Helm repository and update it:
helm repo add gatekeeper https://open-policy-agent.github.io/gatekeeper/charts
helm repo update
2. Install Gatekeeper using helm
Install Gatekeeper in the gatekeeper-system
namespace (it will be created if it doesn’t exist):
helm install -n gatekeeper-system gatekeeper gatekeeper/gatekeeper --create-namespace
3. Verify the Installation
Use kubectl
to check if the installation was successful and if Gatekeeper’s deployments are available:
kubectl get deployments -n gatekeeper-system
1. Create a Constraint Template
A Constraint Template defines a reusable policy using Rego. Let’s create a policy to enforce that all Pods must specify resource limits. Learn more about Rego
apiVersion: templates.gatekeeper.sh/v1beta1
kind: ConstraintTemplate
metadata:
name: passlabel
spec:
crd:
spec:
names:
kind: PassLabel
targets:
- target: admission.k8s.gatekeeper.sh
rego: |
package pass_label
import future.keywords.if
default allow := false
allow if input.review.object.metadata.labels.passlabel
violation[{"msg": msg, "details": {}}] {
not allow
msg := "The passlabel label is required"
}
2. Create a Constraint to Enforce the Policy
A Constraint applies a Constraint Template to enforce the policy in the cluster.
apiVersion: constraints.gatekeeper.sh/v1beta1
kind: PassLabel
metadata:
name: label-1
spec:
match:
kinds:
- apiGroups: [""]
kinds: ["Pod"]
excludedNamespaces:
- kube-system
parameters: {}
3. Test your Gatekeeper Constraint
Try to Create a Pod Without the Required Label
First, apply a Pod definition without the required label:
apiVersion: v1
kind: Pod
metadata:
name: invalid-pod
spec:
containers:
- name: nginx
image: nginx:alpine
Apply the Pod definition:
kubectl apply -f invalid-pod.yaml
The Pod creation will fail with an error:
Error from server (Forbidden): error when creating "invalid.yaml": admission webhook "validation.gatekeeper.sh" denied the request: [label-1] The passlabel label is required
Modify the Pod Definition to Include the Required Label
Now, update the Pod definition to include the required label:
apiVersion: v1
kind: Pod
metadata:
name: valid-pod
labels:
passlabel: required-value # Add this label as required by Gatekeeper
spec:
containers:
- name: nginx
image: nginx:alpine
Now, update the Pod definition to include the required label:
kubectl apply -f valid-pod.yaml
The Pod will now be allowed since it meets the policy requirements.
Beyond basic policy enforcement, OPA can help implement advanced security and governance controls in your Kubernetes cluster. Here are some additional policies you can enforce:
Require Images from a Trusted Registry
Ensure that all container images originate from an approved registry to prevent the use of unverified or vulnerable images.
Restrict Privileged Containers
Block Pods that run as root or request privileged mode, reducing the risk of container breakout attacks.
Enforce Namespace Quotas
Prevent excessive resource usage by enforcing CPU, memory, and storage limits within namespaces.
Label Enforcement
Ensure that all resources, such as Pods, Deployments, and Services, include mandatory labels like env: production
for better organization and policy enforcement.
Open Policy Agent (OPA) with Gatekeeper offers a powerful and scalable way to enforce consistent policies in Kubernetes. By adopting a policy-as-code approach, organizations can define, manage, and enforce security, compliance, and governance policies in an automated and structured manner. This eliminates manual enforcement, reduces human error, and ensures that all workloads adhere to predefined rules.
Implementing policy-as-code with OPA helps create a secure, compliant, and resilient Kubernetes infrastructure while ensuring best practices are consistently applied across all deployments.