Home > Enterprise >  Accessing environment variables from a pod
Accessing environment variables from a pod

Time:11-26

I wrote golang program which fetches values from environment variable set in my system using export var name = somevalue.

cloudType = os.Getenv("CLOUD_TYPE")
clusterRegion = os.Getenv("CLUSTER_REGION")
clusterType = os.Getenv("CLUSTER_TYPE")
clusterName = os.Getenv("CLUSTER_NAME")
clusterID = os.Getenv("CLUSTER_ID")

As mentioned above my program tries to fetch values from env var set in system using getenv func.The program is working good if run it and fetching values from env variables. But When I tried building a image and running it inside a pod it was able to fetch values from the env var. It is giving empty values. Is there any way to access the local env var from the pod?

CodePudding user response:

...haven't set the env var in the pod. I set it locally in my system

Environment variables set on your host are not automatically pass on to the Pod. You can set the env in your spec and access by your container. A common approach to substitute environment variables in the spec with variables on the host is using envsubst < draft-spec.yaml > final-spec.yaml.

CodePudding user response:

It seems you set the env var not in the image.

First, you need ensure that you set up env in your image or pods. In image, you need to use ENV in your Dockerfile. doc. In Kubernetes pod, doc.

Second, you mentioned you want to get runtime env vars from your pod, you can run below command.

kubectl exec -it ${POD_NAME} -- printenv

CodePudding user response:

Make a yaml file like this to define a config map

apiVersion: v1
data:
  CLOUD_TYPE: "$CLOUD_TYPE"
  CLUSTER_REGION: "$CLUSTER_REGION"
  CLUSTER_TYPE: "$CLUSTER_TYPE"
  CLUSTER_NAME: "$CLUSTER_NAME"
  CLUSTER_ID: "$CLUSTER_ID"
kind: ConfigMap
metadata:
  creationTimestamp: null
  name: foo

Ensure your config vars are set then apply it to your cluster, with env substitution first

envsubst < foo.yaml | kubectl apply -f

Then in the pod definition use the config map

spec:
  containers:
  - name: mypod
    envFrom:
    - configMapRef:
        name: foo
  • Related