How to access Kubernetes cluster environment variables within a container?

9/14/2021

For example, I run a Pod in a public cloud cluster. The Pod has a main container running the app. The cluster has an environment variable named ABC. Within the main container, I wish to access the environment variable ABC. What is the best way to do so?

-- jtee
kubernetes

1 Answer

9/14/2021

Very simple option

apiVersion: v1
kind: Pod
metadata:
  name: envar-demo
  labels:
    purpose: demonstrate-envars
spec:
  containers:
  - name: envar-demo-container
    image: gcr.io/google-samples/node-hello:1.0
    env:
    - name: DEMO_GREETING
      value: "Hello from the environment"
    - name: DEMO_FAREWELL
      value: "Such a sweet sorrow"

Read more : https://kubernetes.io/docs/tasks/inject-data-application/define-environment-variable-container/

Option 1

If variables is not much important you can use the configmap to store the and config map will get injected to POD and your app can access the variables from OS.

Read more about configmap : https://kubernetes.io/docs/concepts/configuration/configmap/

Example configmap :

apiVersion: v1
kind: ConfigMap
metadata:
  name: special-config
  namespace: default
data:
  SPECIAL_LEVEL: very
  SPECIAL_TYPE: charm 

example pod

apiVersion: v1
kind: Pod
metadata:
  name: dapi-test-pod
spec:
  containers:
    - name: test-container
      image: k8s.gcr.io/busybox
      command: [ "/bin/sh", "-c", "ls /etc/config/" ]
      volumeMounts:
      - name: config-volume
        mountPath: /etc/config
  volumes:
    - name: config-volume
      configMap:
        # Provide the name of the ConfigMap containing the files you want
        # to add to the container
        name: special-config
  restartPolicy: Never

You can also inject files with list of variables as per requirement.

Option 2 :

You can also use secret if your variable is important : https://kubernetes.io/docs/concepts/configuration/secret/

Option 3 :

If you want to go with best practices and options you can use the vault with Kubernetes for managing all different microservice variables management.

Vault : https://www.vaultproject.io/

Example : https://github.com/travelaudience/kubernetes-vault-example

it key-value pair management and provides good security options also.

-- Harsh Manvar
Source: StackOverflow