Can we read environment variable on Azure Kubernetes Pod?

9/25/2019

We have deployed some of the services (like Web API) on Azure Kubernetes. When we logged onto the Azure Kubernetes Pods and execute the printenv on the terminal, it shows environment variable on the screen including the service we deployed like

<SERVICENAME>_PORT=
<SERVICENAME>_HOST=`
.....

How can we read above variable value in the .Net code? I tried with the below code but it didn't work

 var builder = new ConfigurationBuilder();
            builder.AddJsonFile("appsettings_prod.json", true, true).AddEnvironmentVariables();
            Configuration = builder.Build();

var port =  Configuration["<SERVICENAME>_PORT"] 
-- HowsTheJosh
.net-core
azure-aks
azure-devops
c#
kubernetes

3 Answers

9/25/2019

You can also use downward-api to expose pod information to containers.

-- FL3SH
Source: StackOverflow

9/25/2019

To access env from k8s pods, you need to provide those env through pod's spec.containers[].env[].

apiVersion: v1
kind: Pod
metadata:
  name: demo-pod
spec:
  containers:
  - name: mycontainer
    image: demo/new-image
    env:
      # define env from k8s secret (used specially for credentials)
      - name: SECRET_USERNAME
        valueFrom:
          secretKeyRef:
            name: mysecret
            key: username
      # define env from configmap
      - name: SPECIAL_CREDENTIALS
          valueFrom:
            configMapKeyRef: 
              name: configmap-name
              key: config.json
      # define value directly 
      - name: DEMO_GREETING
        value: "Hello from the environment"
-- Kamol Hasan
Source: StackOverflow

9/25/2019

If you want to pass the environment variable to code you can use the value of config map of kubernetes. it will set the value in environment os of pod and in code you can get it from there.

for secure data you can use the secret.

-- Harsh Manvar
Source: StackOverflow