Kubernetes Kustomize: replace variable in patch file Kubernetes Kustomize: replace variable in patch file kubernetes kubernetes

Kubernetes Kustomize: replace variable in patch file


As @Jonas already suggested you should consider using Secret. It's nicely described in this article.

I want to use kubectl apply -k and somehow pass a value for ${PASSWORD} which I can set from my build script.

I guess your script can store the generated password as a variable or save it to some file. You can easily create a Secret as follows:

$ kustomize edit add secret sl-demo-app --from-literal=db-password=$PASSWORD

or from a file:

$ kustomize edit add secret sl-demo-app --from-file=file/path

As you can read in the mentioned article:

These commands will modify your kustomization.yaml and add a SecretGenerator inside it.

apiVersion: kustomize.config.k8s.io/v1beta1kind: Kustomizationbases:- ../../basepatchesStrategicMerge:- custom-env.yaml- replica-and-rollout-strategy.yamlsecretGenerator:- literals:  - db-password=12345  name: sl-demo-app  type: Opaque

kustomize build run in your project directory will create among others following Secret:

apiVersion: v1data:  db-password: MTIzNDU=kind: Secretmetadata:  name: sl-demo-app-6ft88t2625type: Opaque...

More details you can fine in the article.

If we want to use this secret from our deployment, we just have, like before, to add a new layer definition which uses the secret.

For example, this file will mount the db-password value as environement variables

apiVersion: apps/v1kind: Deploymentmetadata:  name: sl-demo-appspec:  template:    spec:      containers:      - name: app        env:        - name: "DB_PASSWORD"          valueFrom:            secretKeyRef:              name: sl-demo-app              key: db.password

In your Deployment definition file it may look similar to this:

apiVersion: apps/v1kind: Deploymentmetadata:  name: fluxspec:  template:    spec:      containers:        - name: some-name          env:            - name: "PASSWORD"              valueFrom:                secretKeyRef:                  name: git-secret                  key: git.password          args:            - --some-key=some-value            ...            - --git-url=https://user:${PASSWORD}@domain.de