BASH
Securely Managing Environment Variables for Web Deployments
Streamline and secure the handling of application environment variables for different deployment stages using bash scripts, preventing hardcoding sensitive data and enhancing flexibility.
#!/bin/bash
# Configuration
# Define the base directory where your application's .env files reside
APP_ROOT="/var/www/your_app"
# Define the environment you want to load (e.g., 'development', 'staging', 'production')
# This can also be passed as an argument to the script: ./load_env.sh production
ENV_NAME="production"
# --- DO NOT EDIT BELOW THIS LINE ---
# Override ENV_NAME if provided as a command-line argument
if [ -n "$1" ]; then
ENV_NAME="$1"
fi
ENV_FILE="${APP_ROOT}/.env.${ENV_NAME}"
DEFAULT_ENV_FILE="${APP_ROOT}/.env"
if [ ! -f "${ENV_FILE}" ]; then
echo "Warning: Environment file '${ENV_FILE}' not found. Trying default '.env' file." >&2
ENV_FILE="${DEFAULT_ENV_FILE}"
if [ ! -f "${ENV_FILE}" ]; then
echo "Error: Default environment file '${ENV_FILE}' not found either." >&2
exit 1
fi
fi
echo "Loading environment variables from: ${ENV_FILE}"
# Source the environment file
# This makes the variables available in the current shell context
set -a # Automatically export all variables subsequently defined
source "${ENV_FILE}"
set +a # Turn off auto-export
# Verify a variable (example)
# You might use this in a deployment script to ensure critical variables are loaded
if [ -z "$DB_HOST" ]; then
echo "Warning: DB_HOST environment variable not set." >&2
else
echo "DB_HOST is set to: ${DB_HOST}"
fi
# You can now run your application, and it will pick up these variables
# Example: /usr/bin/php ${APP_ROOT}/artisan migrate
# Example: npm start
How it works: This bash script provides a robust way to manage environment variables for web applications across different deployment environments (e.g., development, staging, production). It loads variables from `.env` files (e.g., `.env.production`) specific to the target environment. By 'sourcing' the file (`source "${ENV_FILE}"`), the script makes these variables available in the current shell's environment, avoiding hardcoding sensitive information directly into the application code or deployment scripts. It includes a fallback to a default `.env` file and a mechanism to verify that critical variables are set, enhancing security and deployment consistency.