All Policies

Replace Ingress Hosts

An Ingress may specify host names at a variety of locations in the same resource. In some cases, those host names should be modified to, for example, update domain names silently. The replacement must be done in all the fields where a host name can be specified. This policy, illustrating the use of nested foreach loops and operable in Kyverno 1.9+, replaces host names that end with `old.com` with `new.com`.

Policy Definition

/other/replace-ingress-hosts/replace-ingress-hosts.yaml

 1apiVersion: kyverno.io/v2beta1
 2kind: ClusterPolicy
 3metadata:
 4  name: replace-ingress-hosts
 5  annotations:
 6    policies.kyverno.io/title: Replace Ingress Hosts
 7    policies.kyverno.io/category: Other
 8    policies.kyverno.io/severity: medium
 9    kyverno.io/kyverno-version: 1.9.0
10    policies.kyverno.io/minversion: 1.9.0
11    kyverno.io/kubernetes-version: "1.24"
12    policies.kyverno.io/subject: Ingress
13    policies.kyverno.io/description: >-
14      An Ingress may specify host names at a variety of locations in the same resource.
15      In some cases, those host names should be modified to, for example, update domain names
16      silently. The replacement must be done in all the fields where a host name can be specified.
17      This policy, illustrating the use of nested foreach loops and operable in Kyverno 1.9+, replaces
18      host names that end with `old.com` with `new.com`.      
19spec:
20  background: false
21  rules:
22    - name: replace-old-with-new
23      match:
24        any:
25          - resources:
26              kinds:
27                - Ingress
28      mutate:
29        foreach:
30          - list: request.object.spec.rules
31            patchesJson6902: |-
32              - path: /spec/rules/{{elementIndex}}/host
33                op: replace
34                value: {{replace_all('{{element.host}}', '.old.com', '.new.com')}}              
35          - list: request.object.spec.tls[]
36            foreach:
37              - list: "element.hosts"
38                patchesJson6902: |-
39                  - path: /spec/tls/{{elementIndex0}}/hosts/{{elementIndex1}}
40                    op: replace
41                    value: "{{ replace_all('{{element}}', '.old.com', '.new.com') }}"                  
42          - list: request.object.spec.tls[]
43            patchesJson6902: |-
44              - path: /spec/tls/{{elementIndex}}/secretName
45                op: replace
46                value: "{{ replace_all('{{element.secretName}}', '.old.com', '.new.com') }}"