Automation

Adding environment variable from file in kubernetes


Environment variables plays an important role in micro service pod deployment .In kubernetes pod, we declared all the environment variable in deployment file in the “env:” section .Sometimes it is tedious to cover all of them because each micro service have their own Env key and values . To solve this ,we have to pass the ENV using file as and when required.Today we will discuss on how to pass the ENV variable via file.

I created a file called env_file.properties .In this ,I have added all the environment variables

$cat env_file.properties 
ENV1=VALUE1
ENV2=VALUE2
ENV3=VALUE3

Run the below command .It will create a configmap from file.

kubectl create configmap custom-env-cm 
--from-env-file=<user-dir>/env_file.properties


You can check the newly created config map by using the below command

kubectl get configmap
<list of configmaps>

Also verify the values and configmap once again

kubectl get configmap custom-env-cm -o yaml
apiVersion: v1
data:
  ENV1: VALUE1
  ENV2: VALUE2
  ENV3: VALUE3
kind: ConfigMap
metadata:
  creationTimestamp: "2020-03-12T12:29:54Z"
  name: custom-env-cm
  namespace: default
  resourceVersion: "869827"
  selfLink: /api/v1/namespaces/default/configmaps/stf-env-configmap
  uid: 2d5201f1-645d-11ea-ad46-0800270d5c30

Mention the configmap name in deployment file in “envFrom:” section

containers:
      - name: {{ include "myapp.name" . }}
        image: "{{ .Values.myapp.image.repository }}:{{ .Values.myapp.image.tag }}"
        imagePullPolicy: {{ .Values.myapp.image.pullPolicy }}
        volumeMounts:
         - name: test-mount
           mountPath: /myapp/
        envFrom:
        - configMapRef:
              name: custom-env-cm

Now create a deployment and you will notice that newly added environment variable will be added in to pod container .Verify this with printenv command inside the container.

If the config map no longer reqiured then delete the configmap

kubectl delete configmap <configmap name>

Hope you all understand this .Let me know if you have any questions .

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.