Define Program Environment Variables¶
This section guides software developers on how to securely store sensitive information, like access tokens, in environment variables. These practices are crucial for security and are explained for various operating systems, shells, and cloud services, suitable for developers of all skill levels.
Defining Environment Variables in Python¶
In Python, environment variables can be defined using the os.environ dictionary. To set an environment variable named MY_VARIABLE, use the following code:
import os
os.environ["MY_VARIABLE"] = "value"
Alternatively, use the python-dotenv library for a more secure approach. This library enables you to define environment variables in a .env file, which can then be loaded into your Python script:
# Add this line to your .env file located in ~/
MY_VARIABLE="value"
Load the environment variables using the dotenv module:
from dotenv import load_dotenv
load_dotenv()
To access environment variables in Python:
import os
my_variable = os.environ.get("MY_VARIABLE")
if my_variable:
print("MY_VARIABLE is set to:", my_variable)
else:
print("MY_VARIABLE is not set.")
Defining Persistent Environment Variables in Unix¶
For Unix systems, define persistent environment variables in your shell profile file. The file’s location and name depend on your shell. For example, use .bashrc for bash or .zshrc for zsh, both located in your home directory (~/).
Example for bash:
# Add this to your .bashrc file
export MY_VARIABLE="value"
Defining Temporary Environment Variables in Bash Script¶
To define environment variables in a Bash script, use the export keyword:
export MY_VARIABLE="value"
my_variable=$MY_VARIABLE
if [ -n "$my_variable" ]; then
echo "MY_VARIABLE is set to: $my_variable"
else
echo "MY_VARIABLE is not set."
Defining Environment Variables in Windows¶
Use a batch file (.bat) to define environment variables in Windows. The set command sets the variable:
@echo off
set MY_VARIABLE=value
if errorlevel 1 (
echo MY_VARIABLE could not be set
) else (
echo MY_VARIABLE was set successfully
)
For persistent variables:
Open “Environment Variables” from the Start menu.
Click “Edit the system environment variables” > “Environment Variables”.
Choose “User variables” or “System variables” to add or edit a variable.
Enter the variable’s name and value, then click “OK”.
Note
Restart command prompt windows to apply new environment variables.