'Replace contents of an item in a list using Kustomize

I'm having difficulty trying to get kustomize to replace contents of an item in a list.

My kustomize file

apiVersion: kustomize.config.k8s.io/v1beta1
kind: Kustomization

resources:
  - resource.yaml

patches:
  - patch.yaml

My patch.yaml file

apiVersion: apps/v1
kind: Deployment
metadata:
  name: web-service
spec:
  template:
    spec:
      initContainers:
        - name: web-service-migration
          env:
            - name: PG_DATABASE
              value: web-pgdb


My resource.yaml

apiVersion: apps/v1
kind: Deployment
metadata:
  name: web-service
spec:
  template:
    spec:
      initContainers:
        - name: web-service-migration
          env:
            - name: PG_DATABASE
              valueFrom:
                secretKeyRef:
                  name: web-pgdb
                  key: database


kustomize build returns

apiVersion: apps/v1
kind: Deployment
metadata:
  name: web-service
spec:
  template:
    spec:
      initContainers:
      - env:
        - name: PG_DATABASE
          value: web-pgdb
          valueFrom:
            secretKeyRef:
              key: database
              name: web-pgdb
        name: web-service-migration

what i want kustomize build to return

apiVersion: apps/v1
kind: Deployment
metadata:
  name: web-service
spec:
  template:
    spec:
      initContainers:
      - env:
        - name: PG_DATABASE
          value: web-pgdb
        name: web-service-migration


Solution 1:[1]

If I remember correctly patches in kustomize by default uses strategic merge, so you need to nullify valueFrom, so your patch should look like:

apiVersion: apps/v1
kind: Deployment
metadata:
  name: web-service
spec:
  template:
    spec:
      initContainers:
        - name: web-service-migration
          env:
            - name: PG_DATABASE
              value: web-pgdb
              valueFrom: null 

More details about strategic merge patch and how to delete maps: https://github.com/kubernetes/community/blob/master/contributors/devel/sig-api-machinery/strategic-merge-patch.md#maps

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1