All Policies

Annotate Base Images

A base image used to construct a container image is not accessible by any Kubernetes component and not a field in a Pod spec as it must be fetched from a registry. Having this information available in the resource referencing the containers helps to provide a clearer understanding of its contents. This policy adds an annotation to a Pod or its controllers with the base image used for each container if present in an OCI annotation.

Policy Definition

/other-mpol/annotate-base-images/annotate-base-images.yaml

 1apiVersion: policies.kyverno.io/v1alpha1
 2kind: MutatingPolicy
 3metadata:
 4  name: annotate-base-images
 5  annotations:
 6    policies.kyverno.io/title: Annotate Base Images
 7    policies.kyverno.io/category: Other
 8    policies.kyverno.io/severity: medium
 9    pod-policies.kyverno.io/autogen-controllers: none
10    policies.kyverno.io/minversion: 1.7.0
11    policies.kyverno.io/subject: Pod
12    policies.kyverno.io/description: >-
13      A base image used to construct a container image is not accessible
14      by any Kubernetes component and not a field in a Pod spec as it must
15      be fetched from a registry. Having this information available in the resource
16      referencing the containers helps to provide a clearer understanding of
17      its contents. This policy adds an annotation to a Pod or its controllers
18      with the base image used for each container if present in an OCI annotation.
19spec:
20  evaluation:
21    admission:
22      enabled: true
23  matchConstraints:
24    resourceRules:
25    - apiGroups: [""]
26      apiVersions: ["v1"]
27      operations: ["CREATE", "UPDATE"]
28      resources: ["pods"]
29  variables:
30    - name: imageMetadata
31      expression: >-
32        object.spec.containers.map(c, image.GetMetadata(c.image))
33  mutations:
34  # First, ensure annotations exist
35  - patchType: JSONPatch
36    jsonPatch:
37      expression: |
38        !has(object.metadata.annotations) ?
39        [
40          JSONPatch{
41            op: "add",
42            path: "/metadata/annotations",
43            value: {}
44          }
45        ] : []
46  # Then add base image annotations for each container
47  - patchType: JSONPatch
48    jsonPatch:
49      expression: |
50        variables.imageMetadata.map(img, variables.imageMetadata.indexOf(img)).map(idx,
51          has(variables.imageMetadata[idx].manifest) && 
52          has(variables.imageMetadata[idx].manifest.annotations) &&
53          "org.opencontainers.image.base.name" in variables.imageMetadata[idx].manifest.annotations ?
54          JSONPatch{
55            op: "add",
56            path: "/metadata/annotations/" + jsonpatch.escapeKey("kyverno.io/baseimages" + string(idx)),
57            value: variables.imageMetadata[idx].manifest.annotations["org.opencontainers.image.base.name"]
58          } : null
59        ).filter(p, p != null)