title: “Open Policy Agent (OPA)”
date: 2020-12-13T18:08:39
slug: open-policy-agent-opa
Install OPA: kubectl create -f https://raw.githubusercontent.com/killer-sh/cks-course-environment/master/course-content/opa/gatekeeper.yaml
Create DenyAll Policy for Pods: https://github.com/killer-sh/cks-course-environment/tree/master/course-content/opa/deny-all
https://play.openpolicyagent.org
https://github.com/BouweCeunen/gatekeeper-policies
https://github.com/open-policy-agent/gatekeeper-library/tree/master/library/general
https://github.com/open-policy-agent/gatekeeper/tree/master/demo/basic
Example required memorylimit:
cat requiredresources-template.yaml
apiVersion: templates.gatekeeper.sh/v1beta1
kind: ConstraintTemplate
metadata:
name: k8srequiredresources
spec:
crd:
spec:
names:
kind: K8sRequiredResources
listKind: K8sRequiredResourcesList
plural: k8srequiredresources
singular: k8srequiredresources
validation:
# Schema for the `parameters` field
openAPIV3Schema:
properties:
requests\_cpu:
type: string
requests\_memory:
type: string
limits\_cpu:
type: string
limits\_memory:
type: string
targets:
- target: admission.k8s.gatekeeper.sh
rego: |
package k8srequiredresources
violation[{"msg": msg}] {
container := input.review.object.spec.containers[\_]
#not container.resources.limits
not container.resources.limits.memory
msg := sprintf("container <%v> has no memory limits", [container.name])
}
cat resources-policy.yml
apiVersion: constraints.gatekeeper.sh/v1beta1
kind: K8sRequiredResources
metadata:
name: resources-policy
spec:
match:
kinds:
- apiGroups: ["batch", "extensions", "apps", ""]
kinds: ["Deployment", "Pod", "CronJob", "Job", "StatefulSet", "DaemonSet"]
