Environment variable hygiene
Undefined environment variables fail silently in most shells, leading to subtle bugs. Use strict variable checking to catch errors early.
Context
Shell scripts and CI/CD workflows often depend on environment variables for configuration, secrets, and runtime parameters. By default, referencing an undefined variable returns an empty string rather than failing, causing hard-to-debug issues.
Problem
# .github/workflows/deploy.yml - WRONG: Using undefined variable
env:
GITHUB_TOKEN: ${{ secrets.GH_TOKEN }} # GH_TOKEN doesn't exist!
# The workflow runs but GITHUB_TOKEN is empty
# API calls fail with cryptic "401 Unauthorized" errors
# Debugging takes hours to discover the typoIn this case, the actual secret was named ORG_PAT, not GH_TOKEN. The workflow appeared to run but failed silently on authenticated API calls.
Solution
- Enable strict mode in bash scripts:
#!/bin/bash
set -euo pipefail
# -e: Exit on error
# -u: Error on undefined variables
# -o pipefail: Exit on pipe failures
# Now this fails immediately with clear error message:
echo "Token: $UNDEFINED_VAR"
# Error: UNDEFINED_VAR: unbound variable- Add validation at script start:
# Validate required variables explicitly
: "${GITHUB_TOKEN:?GITHUB_TOKEN must be set}"
: "${RUNNER_NAME:?RUNNER_NAME must be set}"
# Now script only proceeds if all required vars are defined- Use GitHub Actions variable validation:
- name: Validate required secrets
run: |
if [ -z "${{ secrets.ORG_PAT }}" ]; then
echo "::error::ORG_PAT secret is not configured"
exit 1
fi- Document expected variables:
# Required environment variables:
# GITHUB_TOKEN - Personal access token with repo scope
# RUNNER_NAME - Name for this runner instance
# RUNNER_LABELS - Comma-separated runner labelsReusability
- Score: 5/5
- Used in: aloysiusproductions-ops-core workflows and scripts
Trade-offs
- Pro: Fails fast with clear error messages
- Pro: Prevents silent failures and data corruption
- Pro: Documents required configuration
- Con: May break existing scripts that rely on undefined-as-empty
- Con: Requires updating existing scripts to be strict
Source
Discovered during workflow audit on 2026-01-23. Commit a4e6515 fixed GH_TOKEN → ORG_PAT typo that caused silent authentication failures.
Related
- ops-core - Central infrastructure patterns
- CD patterns - Related automation patterns