Kubernetes Kustomize: replace variable in patch file

1/14/2020

Given the following kustomize patch:

apiVersion: apps/v1
kind: Deployment
metadata:
  name: flux
spec:
  template:
    spec:
      containers:
        - name: some-name
          args:
            - --some-key=some-value
            ...
            - --git-url=https://user:${PASSWORD}@domain.de

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

The only solution I got to work so far was replacing the ${PASSWORD} with sed, but I would prefer a kustomize solution.

-- user2074945
kubernetes
kustomize

1 Answer

1/15/2020

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/v1beta1
kind: Kustomization

bases:
- ../../base

patchesStrategicMerge:
- custom-env.yaml
- replica-and-rollout-strategy.yaml

secretGenerator:
- literals:
  - db-password=12345
  name: sl-demo-app
  type: Opaque

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

apiVersion: v1
data:
  db-password: MTIzNDU=
kind: Secret
metadata:
  name: sl-demo-app-6ft88t2625
type: 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/v1
kind: Deployment
metadata:
  name: sl-demo-app
spec:
  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/v1
kind: Deployment
metadata:
  name: flux
spec:
  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
-- mario
Source: StackOverflow