I have some Python project, like a library. I have also two Azure DevOps environment feeds, NPRD and PROD for example. There are two different pipelines for build and post artifacts.
Now I need to define some different constants in my code for these envs, like URLS, end-points, etc. Maybe part of them I want to be secured. My built artifact (whl actually) will work on some user machine which I don't have access to and I can't define environment variables for my properties.
So how can I inject these values to the project during pipeline build? Is it possible?
1 Replies
A better way to manage your environment variables is to store them in a .env
(pronounced dot env) file.
A .env
file is a text file in which the variables are defined, one per line. The format of a .env
file is exactly the same under all operating systems, so .env
files make working with environment variables uniform across all platforms. And as if this isn’t enough, having your environment variables written in a file that is automatically imported by Python means that you don’t have to manually set them every time you start a new shell.
You can create a .env
file in the root directory of each of your projects, and that way you can keep all the variables that are needed by each project neatly organized!
The python-dotenv package allows a Python application to import variables defined in a .env
file into the environment. You can install python-dotenv
in your virtual environment using pip:
pip install python-dotenv
from dotenv import load_dotenv
load_dotenv('/home/miguel/my_project/.env')
os.environ['ENV_VAR_NAME']
To set the value to the environment user variable:
os.environ['USER'] = 'Bob'
If you need to clear a single environment variable in the session you can use os.environ.pop()
with the key and if you need to clear all environment variables you can use os.environ.clear()
os.environ.pop('USER')
os.environ.clear()
environment variables can be called like so:
From dotenv import load_dotenv
load_dotenv()
import os
token = os.environ.get("USER")
Hope this will help you.