Certified Kubernetes Security Specialist (CKS) Preparation Part 6 — Open Policy Agent (OPA)

kubectl apply -f https://raw.githubusercontent.com/open-policy-agent/gatekeeper/master/deploy/gatekeeper.yaml
- kubectl get ns
- kubectl get all -n gatekeeper-system
deny[msg] {
# `input` is a global variable bound to the data sent to OPA by Kubernetes. In Rego,
# the `.` operator selects keys from objects. If a key is missing, no error
# is generated. The statement is just undefined.
value := input.request.object.metadata.labels.costcenter
# Check if the label value is formatted correctly.
not startswith(value, "cccode-")
# Construct an error message to return to the user.
msg := sprintf("Costcenter code must start with `cccode-`; found `%v`", [value])
}
{
"deny": [
"Costcenter code must start with `cccode-`; found `fakecode`"
]
}
kubectl apply -f https://raw.githubusercontent.com/open-policy-agent/gatekeeper/master/demo/basic/templates/k8srequiredlabels_template.yaml
kubectl get crd
kubectl apply -f https://raw.githubusercontent.com/open-policy-agent/gatekeeper/master/demo/basic/constraints/all_ns_must_have_gatekeeper.yaml
kubectl get k8srequiredlabels
kubectl create ns test
  • Ensure the JSON object is in the correct format for both constraint templates and constraints
  • Test out the constraint logics within Rego Playground
  • Deploy in the actual running environment

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Jonathan

Jonathan

Learning new things about Kubernetes every day. Hopefully, the learning notes could help people on the same journey!