Search code examples
kubernetesenvironment-variableskubernetes-secrets

how to refer for a secret object having environment variables inside a container


I have a question and I hope anyone can help me. well, I have a deployment YAML file having a pod for an application and this app must be connected with redisDB using environment variables, I already setting the environment variables on the pod as u see here :

spec:
      containers:
      - name: app
        image: nix/python
        ports:
          - containerPort: 8000
        imagePullPolicy: Always
        env:
          - name: ENVIRONMENT
            value: "DEV"
          - name: HOST
            value: "localhost"
          - name: PORT
            value: "8000"
          - name: REDIS_HOST
            value: "nix"
          - name: REDIS_PORT
            value: "6379"
          - name: REDIS_DB
            value: "0"

but I think it's not a best practice as a secure way, so I am thinking of defining those environments all into a secret object and referring to it under the container env. I just wanna refer to the name of the secret name and the container must read all the variables all at once not one by one. so how to make it plz ?


Solution

  • Replace the env field with this:

    envFrom:
    - secretRef:
        name: {{ .name }}
        optional: false
    

    Set {{ .name }} to the name of the secret object you create.

    You secret object should look like this:

    apiVersion: v1
    kind: Secret
    metadata:
      name: {{ .name }}
    type: Opaque
    stringData:
      ENVIRONMENT: "DEV"
      HOST: "localhost"
      PORT: "8000"
      REDIS_HOST: "nix"
      REDIS_PORT: "6379"
      REDIS_DB: "0"