apiVersion: kyverno.io/v1
kind: ClusterPolicy
metadata:
  annotations:
    policies.kyverno.io/description: Adds a firmware serial number to new VirtualMachines if missing.
  name: add-vm-firmware-serial-if-missing
spec:
  admission: true
  background: true
  emitWarning: false
  rules:
    - context:
        - name: randomserial
          variable:
            jmesPath: 'random(''[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}'')'
      match:
        resources:
          kinds:
            - VirtualMachine
      mutate:
        patchStrategicMerge:
          spec:
            template:
              spec:
                domain:
                  firmware:
                    +(serial): '{{ randomserial }}'
      name: add-serial-if-missing
      preconditions:
        all:
          - key: '{{ request.operation }}'
            operator: Equals
            value: CREATE
      skipBackgroundRequests: true
  validationFailureAction: Audit
