All Policies

Update Image Tag

For use cases like sidecar injection, it is often the case where existing Deployments need the sidecar image updated without destroying the whole Deployment or Pods. This policy updates the image tag on containers named vault-agent for existing Deployments which have the annotation vault.hashicorp.com/agent-inject="true". It may be necessary to grant additional privileges to the Kyverno ServiceAccount, via one of the existing ClusterRoleBindings or a new one, so it can modify Deployments.

Policy Definition

/other-mpol/update-image-tag/update-image-tag.yaml

 1apiVersion: policies.kyverno.io/v1alpha1
 2kind: MutatingPolicy
 3metadata:
 4  name: update-image-tag
 5  annotations:
 6    policies.kyverno.io/title: Update Image Tag
 7    policies.kyverno.io/category: Other
 8    policies.kyverno.io/severity: medium
 9    policies.kyverno.io/subject: Deployment
10    policies.kyverno.io/description: >-
11      For use cases like sidecar injection, it is often the case where existing
12      Deployments need the sidecar image updated without destroying the whole Deployment
13      or Pods. This policy updates the image tag on containers named vault-agent for
14      existing Deployments which have the annotation vault.hashicorp.com/agent-inject="true".
15      It may be necessary to grant additional privileges to the Kyverno ServiceAccount,
16      via one of the existing ClusterRoleBindings or a new one, so it can modify Deployments.
17spec:
18  evaluation:
19    admission:
20      enabled: true
21    mutateExisting:
22      enabled: true
23  
24  matchConstraints:
25    resourceRules:
26      - apiGroups: ["apps"]
27        apiVersions: ["v1"]
28        resources: ["deployments"]
29        operations: ["CREATE", "UPDATE"]
30  
31  matchConditions:
32    - name: has-vault-inject-annotation
33      expression: "has(object.metadata.annotations) && object.metadata.annotations['vault.hashicorp.com/agent-inject'] == 'true'"
34  
35  variables:
36    - name: containers
37      expression: "object.spec.template.spec.containers"
38    
39    - name: vaultAgentIndex
40      expression: >-
41        variables.containers.map(c, c.name).indexOf('vault-agent')
42    
43    - name: hasVaultAgent
44      expression: "variables.vaultAgentIndex >= 0"
45  
46  mutations:
47    - patchType: JSONPatch
48      jsonPatch:
49        expression: >-
50          variables.hasVaultAgent ?
51          [
52            JSONPatch{
53              op: "replace",
54              path: "/spec/template/spec/containers/" + string(variables.vaultAgentIndex) + "/image",
55              value: "vault:1.5.4"
56            }
57          ] : []