Kustomize dynamic resource names

I have been trying to find a way to dynamically change the resource names in my yaml where I could update the nameSuffix/prefix and not have to modify specific names inside of the kustomized files. Ideally, I’d be able to do this dynamically and not have to change these things manually. My kustomiization looks like this:

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

namespace: vscode-server-dev 

commonLabels:
  app: vscode-dev

commonAnnotations:
  app: vscode-dev-app

namePrefix:
  vscode-

nameSuffix:
  -dev-v1

resources:
- ../../base

patches:
- path: vscode.dev.deployment.yaml
  target:
    kind: Deployment
- path: vscode.dev.storage.yaml
  target:
    kind: StorageClass
- path: vscode.dev.pv.yaml
  target:
    kind: PersistentVolume
- path: vscode.dev.pvc.yaml
  target:
    kind: PersistentVolumeClaim

So in this example, my StorageClass is dynamically named to: vscode-storage-dev-v1 and I’d like to be able to have my PV, PVC, and deployment be able to pick up that this has changed. Currently, when I look at the yaml output using kubectl kustomize . from within my dev overlays folder, it outputs what I expect:

---
apiVersion: v1
kind: PersistentVolume
metadata:
  annotations:
    app: vscode-dev-app
  labels:
    app: vscode-dev
  name: vscode-pv-dev-v1
spec:
  accessModes:
  - ReadWriteOnce
  capacity:
    storage: 1Gi
  local:
    path: /data-dev
  nodeAffinity:
    required:
      nodeSelectorTerms:
      - matchExpressions:
        - key: kubernetes.io/hostname
          operator: In
          values:
          - node3
  persistentVolumeReclaimPolicy: Retain
  storageClassName: vscode-storage-dev-v1

However, within my deployment, the persistentVolumeClaim.name does not match what I expect with the new name.

--snippet--
volumeMounts:
- mountPath: /home/storage/vscode
  name: vscode-storage
volumes:
- name: vscode-storage
  persistentVolumeClaim:
    claimName: vscode.storage.pvc

Is there a way to dynamically set these types of names when using kustomize? I’ve been unable to find a solution and I have other places this could be changed, specifically secrets and certificates.

I tried running the above using k apply -k . from within my dev overlay but was not successful and its using the old name that I had stated.

I looked online, and used chatGPT with little luck.

Leave a Comment