Create kubernetes env var secrets from .env file

11/17/2020

I have a nodejs application which stores variables in environment variables.

I'm using the dotenv module, so I have a .env file that looks like :

VAR1=value1
VAR2=something_else

I'm currently setting up a BitBucket Pipeline to auto deploy this to a Kubernetes cluster.
I'm not very familiar with kubernetes secrets, though I'm reading up on them.

I'm wondering :

Is there an easy way to send to a Docker-container / kubernetes-deployment all of the environment variables I have defined in my .env file so they are available in the pods my app is running in ?

I'm hoping for an example secrets.yml file or similar which takes everything from .env and makes in into environment variables in the container. But it could also be done in the BitBucket pipeline level, or at the Docker container level .. I'm not sure ...

-- kris
bitbucket
docker
environment-variables
kubernetes
node.js

1 Answer

11/17/2020

Step 1: Create a k8s secret with your .env file:

# kubectl create secret generic <secret-name> --from-env-file=<path-to-env-file> 

$ kubectl create secret generic my-env-list --from-env-file=.env 
secret/my-env-list created

Step 2: Varify secret:

$ kubectl get secret my-env-list -o yaml
apiVersion: v1
data:
  VAR1: dmFsdWUx
  VAR2: c29tZXRoaW5nX2Vsc2U=
kind: Secret
metadata:
  name: my-env-list
  namespace: default
type: Opaque

Step 3: Add env to your pod's container:

apiVersion: v1
kind: Pod
metadata:
  name: demo-pod
spec:
  containers:
    - name: demo-container
      image: k8s.gcr.io/busybox
      command: [ "/bin/sh", "-c", "env" ]
      envFrom:
      - secretRef:
          name: my-env-list # <---- here
  restartPolicy: Never

Step 4: Run the pod and check if the env exist or not:

$ kubectl apply -f pod.yaml 
pod/demo-pod created

$ kubectl logs -f demo-pod 
KUBERNETES_PORT=tcp://10.96.0.1:443
KUBERNETES_SERVICE_PORT=443
HOSTNAME=demo-pod
SHLVL=1
HOME=/root
KUBERNETES_PORT_443_TCP_ADDR=10.96.0.1
VAR1=value1  # <------------------------------------------------------here 
VAR2=something_else # <-----------------------------------------------here
PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
KUBERNETES_PORT_443_TCP_PORT=443
KUBERNETES_PORT_443_TCP_PROTO=tcp
KUBERNETES_PORT_443_TCP=tcp://10.96.0.1:443
KUBERNETES_SERVICE_PORT_HTTPS=443
PWD=/
KUBERNETES_SERVICE_HOST=10.96.0.1
-- Kamol Hasan
Source: StackOverflow