Add environment variable to Kubernetes StatefulSet with Kustomize

11/3/2021

I have a StatefulSet like this:

apiVersion: apps/v1
kind: StatefulSet
metadata:
  namespace: myns
  name: myapp
spec:
  replicas: 3
  template:
    spec:
      containers:
      - name: mycontainer
        image: ...
        ...
        env:
        - name: MY_ENV1
          value: "1"

Now I want to add via Kustomize a second environment variable because it is used only in the dev environment. I did something like this:

namespace: myns

resources:
...

patches:
- patch: |-
    - op: add
      path: "/spec/template/spec/containers/0/env/-"
      value:
        - name: MY_ENV2
          value: "2"
  target:
    kind: StatefulSet
    namespace: myns
    name: myapp

The problem is that it doesn't work. If I run kustomize build I don't see this additional variable (I see other variations).

Can anyone help me to understand how to implement it?

-- Salvatore D'angelo
kubernetes
kustomize

2 Answers

11/11/2021

The problem with the issue was that I forgot to add version: v1 in the target section of the patch. Then you should also remove the - in front of the tag name in the value section. The result should be something like this:

apiVersion: apps/v1
kind: StatefulSet
metadata:
  namespace: myns
  name: myapp
spec:
  replicas: 3
  template:
    spec:
      containers:
      - name: mycontainer
        image: ...
        ...
        env:
        - name: MY_ENV1
          value: "1"

here the kustomization.yamlfile:

namespace: myns

resources:
...

patches:
- patch: |-
    - op: add
      path: "/spec/template/spec/containers/0/env/-"
      value:
        name: MY_ENV2
        value: "2"
  target:
    kind: StatefulSet
    namespace: myns
    name: myapp

This worked fine for my original question. I have now a similar problem where this time I need to replace an existing environment variable in the base deployment.

-- Salvatore D'angelo
Source: StackOverflow

11/3/2021

I would consider to use envFrom in your StatefulSet to load the variables from a ConfigMap, then you can use a configMapGenerator with N number of literals.

See Configure all key-value pairs in a ConfigMap as container environment variables for example of envFrom:

Use envFrom to define all of the ConfigMap's data as container environment variables. The key from the ConfigMap becomes the environment variable name in the Pod.

configMapGenerator is a good way to generate this ConfigMap. It can be done many different ways, but here is an example with literals - from the same documentation page, but adapted to your example:

cat <<EOF >./kustomization.yaml
configMapGenerator:
- name: example-configmap-2
  literals:
  - MY_ENV1=Foo
  - MY_ENV2=Bar
EOF
-- Jonas
Source: StackOverflow