OPA Gatekeeper
Using OPA Gatekeeper to apply policy
The following example shows how you can stop accidental deployment of kubernetes resources into the default namespace.
Installing Gatekeeper
kubectl apply -f https://raw.githubusercontent.com/open-policy-agentgatekeeper/v3.20.1/deploy/gatekeeper.yaml
Creating a Policy Template
apiVersion: templates.gatekeeper.sh/v1
kind: ConstraintTemplate
metadata:
name: k8sblockdefaultnamespace
spec:
crd:
spec:
names:
kind: K8sBlockDefaultNamespace
validation:
openAPIV3Schema:
type: object
properties:
exemptResources:
type: array
items:
type: string
exemptNamespaces:
type: array
items:
type: string
targets:
- target: admission.k8s.gatekeeper.sh
rego: |
package k8sblockdefaultnamespace
# Helpers
ns := input.review.namespace
kind := input.review.kind.kind
apiGroup := input.review.kind.group
# Violate if namespace is "default" (even when object.metadata.namespace is omitted),
# unless resource or namespace are exempt.
violation[{"msg": msg}] {
ns == "default"
msg := sprintf("Creation of %s/%s in the 'default' namespace is not allowed.", [apiGroup, kind])
}
Creating a Policy Constraint
apiVersion: constraints.gatekeeper.sh/v1beta1
kind: K8sBlockDefaultNamespace
metadata:
name: block-default-namespace-resources
spec:
match:
kinds:
- apiGroups: [""]
kinds: ["Pod", "Service", "ConfigMap", "Secret"]
- apiGroups: ["apps"]
kinds: ["Deployment", "ReplicaSet", "DaemonSet", "StatefulSet"]
- apiGroups: ["batch"]
kinds: ["Job", "CronJob"]