We described what OPA Gatekeeper is and how it works in an earlier post. In this piece, we will demonstrate with our use case.
lets start:-
Step 1:- Install gatekeeper on kubernetes cluster.
Step 2:- lets create a ConstraintTemplate ConstraintTemplate.yaml
in our Kubernetes Cluster
# ConstraintTemplate.yaml
# ---------------------------------------------------------------
apiVersion: templates.gatekeeper.sh/v1
kind: ConstraintTemplate # Template Identifying Info
metadata:
name: k8srequiredlabels
# ----------------------------------------------------------------
spec:
crd:
spec:
names:
kind: K8sRequiredLabels # Template values for constraint crd's
validation:
# Schema for the `parameters` field
openAPIV3Schema:
type: object
properties:
labels:
type: array
items:
type: string
# ----------------------------------------------------------------
targets:
- target: admission.k8s.gatekeeper.sh
rego: | # 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])
}
# ---------------------------------------------------------------
kubectl create -f ConstraintTemplate.yaml
kubectl get constrainttemplate
Step 3:- Now create a constraint will will enforce policy
we set a policy that requires a pod to contain the label "app"
pod-must-have-app-label.yaml
apiVersion: constraints.gatekeeper.sh/v1beta1
kind: K8sRequiredLabels
metadata:
name: pod-must-have-app-label
spec:
match:
kinds:
- apiGroups: [""]
kinds: ["pod"]
parameters:
labels: ["app"]
kubectl create -f pod-must-have-app-label.yaml
Step 4:- lets create some pods to test this constraint
kubectl run nginx --image=nginx -n test
lets add a label with this pod
its working
There are number of usecases that we can add like
- Policy to make sure replica limits are defined for deployments.
- Policy to make sure that health check probes are defined.
- policy to make sure that namespace are created with labels
you can create your custom policy as well as per your usecase and requirement
Thanks for reading this post
References:-
https://github.com/open-policy-agent/gatekeeper
https://open-policy-agent.github.io/gatekeeper/website/docs/