Devnet
Managing-Secrets-and-Keys
Environment Variable

Environment Variables in Linux Shell

On a Linux operating system, shell variables hold information, such as $HOME, representing the user's home directory. Environment variables, a subset of shell variables, are accessible across shells and subprocesses. They facilitate dynamic configuration without hardcoding values directly into the code.

export SERVER_CONFIG_PATH="/home/configs/server"
echo $SERVER_CONFIG_PATH

In the Linux shell, use export to create environment variables. Conventionally, variable names are uppercase, followed by values separated by an equal sign. The example sets SERVER_CONFIG_PATH, demonstrating how subprocesses inherit these variables.

set
env

Use set to display shell and environment variables, or env to show only environment variables. Changing a variable's value or removing it with unset is common practice to maintain a clean environment.

export SERVER_CONFIG_PATH="/opt/configs/server"
echo $SERVER_CONFIG_PATH

Overwrite variable values as needed. In this case, SERVER_CONFIG_PATH is updated and displayed.

.env File

# .env file
# IP Address
export HOST="192.168.1.10"

# Credentials
export USERNAME="cisco"
export PASSWORD="1234Qwer"

Using a .env file prevents exposing sensitive data in source control. It stores variable names and values, enhancing security.

source .env
echo $HOST

Sourcing .env via the terminal adds variables to the environment. This method ensures consistent configuration across development environments.

Using dotenv Library in Python

pip install python-dotenv

The dotenv library enables loading .env values into Python. After installation, access variables easily in your Python scripts.

from dotenv import dotenv_values
 
config = dotenv_values(".env")
username = config['USERNAME']
password = config['PASSWORD']
host_ip = config['HOST']
print(f"The IP address is {host_ip}. Username: {username}, Password: {password}.")

Utilize the dotenv library to securely manage environment variables in Python applications.

Accessing Environment Variables in Python

import os
 
username = os.environ.get('USERNAME')
password = os.environ.get('PASSWORD')
ip_address = os.environ.get('HOST')
 
# Use retrieved variables in your code

In Python, access environment variables through os.environ. This method ensures data security and separation from source code.

Conclusion

Environment variables offer a flexible way to manage sensitive information in applications. Utilizing .env files and libraries like dotenv enhances security and maintainability. However, be cautious of potential security risks, especially when entering variables directly in the command line.