The Great Cron Job Mystery: When Variables Go AWOL
There I was, 2 AM on a Thursday, staring at logs that made absolutely zero sense. Every cron job was running perfectly - showing "SUCCESS" in the logs - but every single Redis operation was failing with connection errors.
The maintenance service was supposed to clean up stale jobs. The email sync was supposed to process incoming messages. The newsletter generator was supposed to... well, generate newsletters. All of them were running. None of them were working.
Redis Client Error: getaddrinfo ENOTFOUND undefined port 6379
"Undefined"? What kind of host name is "undefined"? I knew the Redis container was running because I could connect to it manually. The environment variables were set in .env.cron
. Everything looked right.
Then it hit me at 2:47 AM. The kind of realization that makes you question your entire career choice.
Environment variables weren't being exported to child processes in the cron environment.
Here's the difference between code that works and code that makes you contemplate a career in goat farming:
## BROKEN: Variables only exist in current shell
source .env.cron
node scheduler.js # Redis connection fails - REDIS_HOST is undefined
## FIXED: Export all variables to child processes
set -a # Enable auto-export of variables
source .env.cron # Now ALL variables get exported
set +a # Disable auto-export (good practice)
node scheduler.js # Success! Redis connects properly
That set -a
flag tells bash to automatically export every variable assignment that follows. Without it, sourcing .env.cron
just sets variables in the current shell - but Node.js runs in a child process that can't see them.
Four hours of debugging. The solution was literally three characters: -a
.
Next time I'll remember that cron environments are basically amnesic shells that forget everything you don't explicitly tell them to remember. (I won't remember this lesson at 2 AM next week, but that's future T's problem.)
Walk safe,