Unlocking the Power of OPA Gatekeeper: Transform Your Kubernetes Experience Today
Introduction :-
Hey there, Kubernetes enthusiasts! Let’s chat about something that’s been making waves in the container orchestration world: OPA Gatekeeper. If you’re like me, you’ve probably heard this term thrown around in tech conversations, but maybe you’re not quite sure what it’s all about. Well, don’t worry — we’re going to break it down together in a way that’s easy to understand and fun to explore.
Gatekeeper Setup: Execute to initiate Gatekeeper setup.
kubectl apply -f https://raw.githubusercontent.com/open-agent/gatekeeper/master/deploy/gate.yaml
The following objects are established post-setup: Run
kubectl get all -n gatekeeper-system
Validation of Admission Control:
Post-installation, the API server invokes the Gatekeeper admission webhook for resource creation, update, or deletion requests within the cluster. Gatekeeper facilitates communication between the API server and OPA, enforcing the policies specified by OPA.
CustomResourceDefinition:
The CustomResourceDefinition (CRD) API permits custom resource definitions. Creating a CRD establishes a new resource according to the specified name and schema.
Gatekeeper employs CRDs, allowing us to define ConstraintTemplates and Constraints to regulate policies on Kubernetes resources like Pods, Deployments, and Jobs.
Various CRDs are configured during installation: Execute
kubectl get crd | grep -i gatekeeper
Name
Creation Timestamp
assign.mutations.gatekeeper.sh 2022–11–29T07:04:42Z
assignmetadata.mutations.gatekeeper.sh 2022–11–29T07:04:43Z
configs.config.gatekeeper.sh 2022–11–29T07:04:43Z
constraintpodstatuses.status.gatekeeper.sh 2022–11–29T07:04:43Z
constrainttemplatepodstatuses.status.gatekeeper.sh 2022–11–29T07:04:43Z
constrainttemplates.templates.gatekeeper.sh 2022–11–29T07:04:44Z
expansiontemplate.expansion.gatekeeper.sh 2022–11–29T07:04:44Z
modifyset.mutations.gatekeeper.sh 2022–11–29T07:04:44Z
mutatorpodstatuses.status.gatekeeper.sh 2022–11–29T07:04:44Z
providers.externaldata.gatekeeper.sh 2022–11–29T07:04:44Z
Among these, constrainttemplates.templates.gatekeeper.sh
allows the creation of Constraints and Constraint Templates for Gatekeeper:
From: https://dev.to/ashokan/kubernetes-policy-management-ii-opa-gatekeeper-465g
- ConstraintTemplates describe methods for validating Kubernetes objects in Gatekeeper’s admission controller, comprising:
- Rego code specifying policy breaches.
- Schema applicable to a Constraint object, as an instantiation of a ConstraintTemplate.
- Constraint outlines requirements a system must satisfy, instructing Gatekeeper on ConstraintTemplate enforcement.
From: https://grumpygrace.dev/posts/intro-to-gatekeeper-policies/
Below is a depiction of CRD, Constraint Template, and Constraint relationships:
Walkthrough:
To enforce a policy ensuring Kubernetes entities (like pods, namespaces) have specific labels, first formulate a ConstraintTemplate and subsequently a Constraint:
ConstraintTemplate:
Here is the ConstraintTemplate.yaml
for creating a ConstraintTemplate on a Kubernetes cluster:
# ConstraintTemplate.yaml
# ---------------------------------------------------------------
apiVersion: templates.gatekeeper.sh/v1
kind: ConstraintTemplate
metadata:
name: k8srequiredlabels
# ----------------------------------------------------------------
spec:
crd:
spec:
names:
kind: K8sRequiredLabels
validation:
openAPIV3Schema:
type: object
properties:
labels:
type: array
items:
type: 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 establish the ConstraintTemplate, apply the manifest:
kubectl create -f ConstraintTemplate.yaml
To view available ConstraintTemplates:
kubectl get ConstraintTemplate
Constraint: Pod Label
Next, establish a Constraint to mandate a pod must include a label titled “app” during creation. Refer to the Constraint file pod-must-have-app-level.yaml
below:
# pod-must-have-app-level.yaml
apiVersion: constraints.gatekeeper.sh/v1beta1
kind: K8sRequiredLabels
metadata:
name: pod-must-have-app-level
spec:
match:
kinds:
- apiGroups: [""]
kinds: ["Pod"]
parameters:
labels: ["app"]
To initiate the Constraint within the Kubernetes cluster:
kubectl create -f pod-must-have-app-level.yaml
Inspect the current Constraints:
kubectl get constraints
Name
Enforcement-Action
Total-Violations
pod-must-have-app-level
Creating a pod without the requisite label:
kubectl run nginx --image=nginx
- Results in: Error from server (Forbidden): admission webhook “validation.gatekeeper.sh” denied the request: [pod-must-have-app-level] you must provide labels: {“app”}
When creating a pod with the required label:
kubectl run nginx --image=nginx --labels=app=test
- Pod creation proceeds smoothly.
Constraint: Namespace Label
A ConstraintTemplate can serve multiple Constraints. Previously, Constraints mandated a pod-specific label; similarly, Constraints may target namespaces with specific labels.
Utilize the ns-must-label-state.yaml
for enforcing namespace labeling:
# ns-must-label-state.yaml
apiVersion: constraints.gatekeeper.sh/v1beta1
kind: K8sRequiredLabels
metadata:
name: ns-must-label-state
spec:
match:
kinds:
- apiGroups: [""]
kinds: ["Namespace"]
parameters:
labels: ["state"]
Deploy the defined Constraint:
kubectl create -f ns-must-label-state.yaml
View current Constraints:
kubectl get constraints
Name
Enforcement-Action
Total-Violations
ns-must-label-state
pod-must-have-app-level
Attempt to create a namespace without the required “state” label:
Result in: Error from server (Forbidden): admission webhook “validation.gatekeeper.sh” denied the request: [ns-must-label-state] you must provide labels: {“state”}
Successfully establishing a namespace with the label:
# test-ns.yaml
apiVersion: v1
kind: Namespace
metadata:
name: test
labels:
state: dev
kubectl create -f test-ns.yaml
- Namespace creation succeeds without issues.
Checking for Violations:
To inspect detailed violations of current Kubernetes resources against Constraints:
kubectl describe <ConstraintTemplate> <Constraint>
Describe the “ns-must-label-state” constraint:
Name: ns-must-label-state
Namespace:
...
...
Status:
Audit Timestamp: 2022-11-30T02:32:48Z
By Pod:
Constraint UID: 846a2d86-5d00-4eba-bd6a-669cd27fc703
Enforced: true
Id: gatekeeper-audit-56ddcd8749-htgk5
Observed Generation: 1
Operations:
audit
mutation-status
status
Constraint UID: 846a2d86-5d00-4eba-bd6a-669cd27fc703
Enforced: true
Id: gatekeeper-controller-manager-64fd6c8cfd-jh7qr
Observed Generation: 1
Operations:
mutation-webhook
webhook
Constraint UID: 846a2d86-5d00-4eba-bd6a-669cd27fc703
Enforced: true
Id: gatekeeper-controller-manager-64fd6c8cfd-q6ds9
Observed Generation: 1
Operations:
mutation-webhook
webhook
Constraint UID: 846a2d86-5d00-4eba-bd6a-669cd27fc703
Enforced: true
Id: gatekeeper-controller-manager-64fd6c8cfd-rbvsz
Observed Generation: 1
Operations:
mutation-webhook
webhook
Total Violations: 5
Violations:
Enforcement Action: deny
Group:
Kind: Namespace
Message: you must provide labels: {"state"}
Name: kube-public
Version: v1
Enforcement Action: deny
Group:
Kind: Namespace
Message: you must provide labels: {"state"}
Name: kube-node-lease
Version: v1
Enforcement Action: deny
Group:
Kind: Namespace
Message: you must provide labels: {"state"}
Name: gatekeeper-system
Version: v1
Enforcement Action: deny
Group:
Kind: Namespace
Message: you must provide labels: {"state"}
Name: kube-system
Version: v1
Enforcement Action: deny
Group:
Kind: Namespace
Message: you must provide labels: {"state"}
Name: default
Version: v1
Events: <none>
The above illustrates several namespaces violating the policy, as they were created before the “ns-must-label-state” constraint was imposed.
Conclusion :-
And there you have it, friends! We’ve taken quite a journey through the world of OPA Gatekeeper and its impact on Kubernetes. I hope you’re feeling as excited about it as I am. Remember, OPA Gatekeeper isn’t just another tool to add to your tech stack — it’s a way to make your Kubernetes experience more secure, compliant, and ultimately, more enjoyable.
Thanks for joining me on this exploration of OPA Gatekeeper. Here’s to smoother, safer Kubernetes experiences for all of us. Happy containerizing!