OPA Gatekeeper — allow image pull policy

Jbn1233
1 min readFeb 2, 2022

another example for more understand the OPA Gatekeeper.

I want to force all pod not to use Always imagePullPolicy.

This is the result.

$ kubectl run nginx1 --image=nginx  --image-pull-policy='Always' 
Error from server ([imagepullpolicy-openpolicyagent] container <nginx1> has an invalid imagePullPolicy <nginx>, allowed imagePullPolicy are ["IfNotPresent"])
$ kubectl run nginx1 --image=nginx --image-pull-policy='IfNotPresent'
pod/nginx1 created

constraint and template file

::::::::::::::
constraint.yaml
::::::::::::::
apiVersion: constraints.gatekeeper.sh/v1beta1
kind: imagepullpolicy
metadata:
name: imagepullpolicy-openpolicyagent
spec:
match:
kinds:
- apiGroups: [""]
kinds: ["Pod"]
parameters:
repos:
- "IfNotPresent"
::::::::::::::
template.yaml
::::::::::::::
apiVersion: templates.gatekeeper.sh/v1beta1
kind: ConstraintTemplate
metadata:
name: imagepullpolicy
annotations:
description: >-
Requires container images to begin with a string from the specified list.
spec:
crd:
spec:
names:
kind: imagepullpolicy
validation:
# Schema for the `parameters` field
openAPIV3Schema:
type: object
properties:
repos:
description: The list of prefixes a container image is allowed to have.
type: array
items:
type: string
targets:
- target: admission.k8s.gatekeeper.sh
rego: |
package imagepullpolicy
violation[{"msg": msg}] {
container := input.review.object.spec.containers[_]
satisfied := [good | repo = input.parameters.repos[_] ; good = startswith(container.imagePullPolicy, repo)]
not any(satisfied)
msg := sprintf("container <%v> has an invalid imagePullPolicy <%v>, allowed imagePullPolicy are %v", [container.name, container.image, input.parameters.repos])
}

As you can see, I just modified from this URL:
https://github.com/open-policy-agent/gatekeeper-library/tree/master/library/general/allowedrepos

That’s all

edit1:

Can be excluded with match

spec:
match:
excludedNamespaces:
- kube-system
- gatekeeper-system
kinds:
- apiGroups:
- ""
kinds:
- Pod

refer: https://cloud.google.com/anthos-config-management/docs/how-to/creating-constraints

--

--

Jbn1233

Very short and simple notes for CKA/SRE and may not works on your environment | jbn1233@gmail.com | Bangkok, Thailand |