How do we dynamically add environment variables in k8s?

In Kubernetes, ConfigMap or Secret can be used to dynamically add environment variables. Here is an example of using ConfigMap and Secret.

  1. Utilize ConfigMap:

First, create a ConfigMap definition file that includes environment variables (e.g. configmap.yaml).

apiVersion: v1
kind: ConfigMap
metadata:
  name: my-configmap
data:
  MY_ENV_VARIABLE: my_value

Next, reference this ConfigMap in the Pod’s spec and add the environment variables to the container.

apiVersion: v1
kind: Pod
metadata:
  name: my-pod
spec:
  containers:
    - name: my-container
      image: my_image
      envFrom:
        - configMapRef:
            name: my-configmap

In this way, the my-container container in the Pod will dynamically add an environment variable named MY_ENV_VARIABLE with a value of my_value.

  1. Use Secret:

Firstly, create a Secret definition file containing environment variables (e.g. secret.yaml).

apiVersion: v1
kind: Secret
metadata:
  name: my-secret
stringData:
  MY_ENV_VARIABLE: my_value

Then, reference this Secret in the spec of the Pod and add the environment variables to the container.

apiVersion: v1
kind: Pod
metadata:
  name: my-pod
spec:
  containers:
    - name: my-container
      image: my_image
      envFrom:
        - secretRef:
            name: my-secret

In this way, the container “my-container” in the Pod will dynamically add an environment variable named MY_ENV_VARIABLE with a value of my_value.

Note that the environment variable names and values in ConfigMap and Secret must be of string type.

bannerAds