Interacting With Environment Variables in Python for App Configuration and Secrets.
Creating .env file
Create a .env
file with your environment variables in the following format:
MY_ENV_VAR = "This is my env var content."
Reading .env file
Install python-dotenv to read the .env file:
pip install python-dotenv
Now you can read the .env
file as follows:
import os
from dotenv import load_dotenv
load_dotenv()
MY_ENV_VAR = os.environ['MY_ENV_VAR']
FAQ
How get GitHub secrets?
Add a new secret, go to your GitHub repository > Settings > Secrets > New Repository Secret
.
Once added, you can then map them as environment variables in your GitHub actions workflow.
- name: Task name
env:
MY_ENV_VAR: ${{ secrets.MY_ENV_VAR }}
run: python your_script.py
import os
from dotenv import load_dotenv
load_dotenv()
MY_ENV_VAR = os.environ['MY_ENV_VAR']
References