How do I load environment variables in main container

Viewed 154

I'm trying to get secrets in init container and pass them to the main container. I have 2 questions here,

  1. How to pass external secrets in init container
  2. How to call them as env variables in main container
1 Answers

you can mount the same secret as Environment variables on both initContainer and mainContainer.

Given a secret such as:

k create secret generic mysecret --from-literal=key=secret

That will be something like:

apiVersion: v1
kind: Pod
metadata:
  creationTimestamp: null
  labels:
    run: mypod
  name: mypod
spec:
  initContainers:
  - name: init
    image: busybox
    env:
    - name: SECRET
      valueFrom:
        secretKeyRef:
          name: mysecret
          key: key
    command: ['sh','-c','echo $SECRET']
  containers:
  - image: busybox
    name: mypod
    resources: {}
    env:
    - name: SECRET
      valueFrom:
        secretKeyRef:
          name: mysecret
          key: key
    command: ['sh','-c','echo $SECRET']
  dnsPolicy: ClusterFirst
  restartPolicy: Never
status: {}

When running the pods, see them both printing the content of the same secret.

kubectl logs mypod -c init
secret

kubectl logs mypod
secret
Related