Kubernetes: extract environment variables from a file when pod kicked off

6/22/2018

I'd like to know whether I'm able to propagate environment variables from a file.

Guess I have a file like this:

ENV_VARIABLE_USERNAME=username
ENV_VARIABLE_PASSWORD=password

I'd like when I pod kicks off, this content file is propagated as environment variables.

Is it possible?

-- Jordi
kubernetes

3 Answers

6/22/2018

I use j2cli and Jinja templates for my Kubernetes manifests. The manifests are written as Jinja templates and j2cli can pass the env vars for me:

j2 --format=env config.j2 data.env

https://github.com/kolypto/j2cli

-- manojlds
Source: StackOverflow

6/22/2018

If your Kubernetes version is higher than 1.6, you can configure your file as a ConfigMap :

kubectl create configmap yourconfigmap --from-env-file=YOUR_ENV_FILE

and then use the content of the configmap in your pod as environment variable

   apiVersion: v1
   kind: Pod
   metadata:
     name: yourpod
   spec:
     containers:
       - name: test-container
         image: yourimage
         command: [ "/bin/sh", "-c", "env" ]
         envFrom:
         - configMapRef:
             name: yourconfigmap
     restartPolicy: Never
-- Nicolas Pepinster
Source: StackOverflow

6/22/2018

Generally speaking, for environment variables, you would do it through a configMap. But as this is a username and password (sensitive information), you can do it through a secret.

For example, given the Pod (redis, for this example) and the Secret below:

apiVersion: v1
kind: Secret
metadata:
  name: credentials
type: Opaque
data:
  username: dXNlcm5hbWU=        //username -> encoded base64
  password: cGFzc3dvcmQ=        //password -> encoded base64

Note: you need to have all data in a secret encoded. This one is encoded with base64:

echo -n username | base64

And the pod:

apiVersion: v1
kind: Pod
metadata:
  name: redis-pod
spec:
  containers:
  - name: redis
    image: redis
    env:
      - name: SECRET_USERNAME
        valueFrom:
          secretKeyRef:
            name: credentials
            key: username
      - name: SECRET_PASSWORD
        valueFrom:
          secretKeyRef:
            name: credentials
            key: password
  restartPolicy: Never

Now if you would run env | grep SECRET in the pod, I would get the variable correctly initialized:

nerus:~/workspace (master) $ kubectl exec redis-pod env | grep SECRET
SECRET_USERNAME=username
SECRET_PASSWORD=password
-- suren
Source: StackOverflow