What would be the opa policy in .rego for the following examples?

7/26/2019

I am new to opa and k8s, i dont have much knowledge or experience in this field. i would like to have policy in rego code (opa policy) and execute to see the result. the following examples are:

  1. Always Pull Images - Ensure every container sets its ‘imagePullPolicy’ to ‘Always’
  2. Check for Liveness Probe - Ensure every container sets a livenessProbe
  3. Check for Readiness Probe - Ensure every container sets a readinessProbe

for the following, i would like have an opa policy:

1.Always Pull Images:

apiVersion: v1
kind: Pod
metadata:
  name: test-image-pull-policy
spec:
  containers:
    - name: nginx
      image: nginx:1.13
      imagePullPolicy: IfNotPresent

2.Check for Liveness Probe

3.Check for Readiness Probe

containers:
- name: opa
  image: openpolicyagent/opa:latest
  ports:
  - name: http
    containerPort: 8181
  args:
  - "run"
  - "--ignore=.*"            # exclude hidden dirs created by Kubernetes
  - "--server"
  - "/policies"
  volumeMounts:
  - readOnly: true
    mountPath: /policies
    name: example-policy
  livenessProbe:
    httpGet:
      scheme: HTTP           # assumes OPA listens on localhost:8181
      port: 8181
    initialDelaySeconds: 5   # tune these periods for your environemnt
    periodSeconds: 5
  readinessProbe:
    httpGet:
      path: /health?bundle=true  # Include bundle activation in readiness
      scheme: HTTP
      port: 8181
    initialDelaySeconds: 5
    periodSeconds: 5

Is there any way to create the opa policy for the above conditions. Could any one help as i am new to opa. Thanks in advance.

-- Keshav
kubernetes
open-policy-agent

2 Answers

8/5/2019
#Always Pull Images 

package kubernetes.admission

deny[msg] {
        input.request.kind.kind = "Pod"
        container = input.request.object.spec.containers[_]
        container.imagePullPolicy != "Always"
        msg = sprintf("Forbidden imagePullPolicy value \"%v\"", [container.imagePullPolicy])
}
-- yman
Source: StackOverflow

8/16/2019

For the liveness and readiness probe checks, you can simply test if those fields are defined:

package kubernetes.admission

deny["container is missing livenessProbe"] {
  container := input_container[_]
  not container.livenessProbe
}

deny["container is missing readinessProbe"] {
  container := input_container[_]
  not container.readinessProbe
}

input_container[container] {
  container := input.request.object.spec.containers[_]
}
-- tsandall
Source: StackOverflow