How to use K8S env variable in python

9/6/2019

I'm deploying my python application in K8S.

I'm passing below env vars in K8S:

env:
    - name: DATA_GET_API
      value: "http://myapi.com/get"
    - name: DATA_PUT_API
      value: "http://myapi.com/put"

How can I use these variables in my python code.

-- rahul s
kubernetes
python

2 Answers

9/6/2019

You can use os.environ:

import os
os.environ['YOUR_CUSTOM_VAR']

Note: before using the above code, make sure that your environmental variables are available by using printenv

-- Peyman.H
Source: StackOverflow

9/6/2019

I guess you are providing these environment variable from pod's spec.

Environment variables can be accessed using os.environ

DataGetAPI = os.environ.get('DATA_GET_API')

DataGetAPI will be set to None if DATA_GET_API is not provided.

You can also set default value when env is not set yet instead of None

DataPutAPI = os.getenv('DATA_PUT_API', default_value)
-- Kamol Hasan
Source: StackOverflow