Created
February 24, 2026 13:50
-
-
Save afreisinger/7584300425c3ef8e78a5ac382fb87f05 to your computer and use it in GitHub Desktop.
Bash script to securely append environment variables with automatically generated strong keys to an existing .env file, preserving existing values. Ideal for Docker Compose secrets management.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/usr/bin/env bash | |
| # append_env_secrets.sh - Append secure keys to an existing .env without overwriting | |
| # List of variables to generate | |
| VARS=("DB_PASSWORD" "SECRET_KEY" "API_TOKEN" "JWT_SECRET" "REDIS_PASSWORD") | |
| # Output file | |
| ENV_FILE=".env" | |
| # Create file if it doesn't exist | |
| touch "$ENV_FILE" | |
| # Add comment header only if not already present | |
| if ! grep -q "# Auto-generated secure keys" "$ENV_FILE"; then | |
| echo "" >> "$ENV_FILE" | |
| echo "# Auto-generated secure keys" >> "$ENV_FILE" | |
| fi | |
| for VAR in "${VARS[@]}"; do | |
| # Check if the variable already exists | |
| if grep -q "^$VAR=" "$ENV_FILE"; then | |
| echo "⚠ $VAR already exists in $ENV_FILE, keeping current value." | |
| else | |
| # Generate a 32-byte base64 key and remove problematic characters | |
| VALUE=$(openssl rand -base64 32 | tr -d '=+/') | |
| echo "$VAR=$VALUE" >> "$ENV_FILE" | |
| echo "✔ $VAR added to $ENV_FILE" | |
| fi | |
| done | |
| echo "Final $ENV_FILE contents:" | |
| cat "$ENV_FILE" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment