apiVersion: kyverno.io/v1
kind: ClusterPolicy
metadata:
  name: add-image-as-env-var
  # env array needs to exist (least one env var is present)
spec:
  background: false
  schemaValidation: false
  rules:
  # One Pod
  - name: pod-containers-1-inject-image
    match:
      any:
      - resources:
          kinds:
          - Pod
    preconditions:
      all:
      - key: "{{request.object.spec.containers[] | length(@)}}"
        operator: GreaterThanOrEquals
        value: 1
    mutate:
      patchesJson6902: |-
        - op: add
          path: "/spec/containers/0/env/-"
          value: {"name":"K8S_IMAGE","value":"{{request.object.spec.containers[0].image}}"}        
  # Two or more Pods
  - name: pod-containers-2-inject-image
    match:
      any:
      - resources:
          kinds:
          - Pod
    preconditions:
      all:
      - key: "{{request.object.spec.containers[] | length(@)}}"
        operator: GreaterThanOrEquals
        value: 2
    mutate:
      patchesJson6902: |-
        - op: add
          path: "/spec/containers/1/env/-"
          value: {"name":"K8S_IMAGE","value":"{{request.object.spec.containers[1].image}}"}        
  # Deployment with one Pod
  - name: deploy-containers-1-inject-image
    match:
      any:
      - resources:
          kinds:
          - Deployment
    preconditions:
      all:
      - key: "{{request.object.spec.template.spec.containers[] | length(@)}}"
        operator: GreaterThanOrEquals
        value: 1
    mutate:
      patchesJson6902: |-
        - op: add
          path: "/spec/template/spec/containers/0/env/-"
          value: {"name":"K8S_IMAGE","value":"{{request.object.spec.template.spec.containers[0].image}}"}        
  # Deployment with two or more Pods
  - name: deploy-containers-2-inject-image
    match:
      any:
      - resources:
          kinds:
          - Deployment
    preconditions:
      all:
      - key: "{{request.object.spec.template.spec.containers[] | length(@)}}"
        operator: GreaterThanOrEquals
        value: 2
    mutate:
      patchesJson6902: |-
        - op: add
          path: "/spec/template/spec/containers/1/env/-"
          value: {"name":"K8S_IMAGE","value":"{{request.object.spec.template.spec.containers[1].image}}"}
