Earlier this week I was completely dumbfounded by a PHP script that launched a Java app that seemed to work fine when it was run from the command line but kept failing when it was run from a cron.
The Java app in question was “ec2-describe-group” out of the Amazon EC2 API Tools package. Basically, the ec2-describe-group tool hits the EC2 API and returns information about your account’s currently configured security groups.
The issue I was having was that when the PHP script was launched from a cron ec2-describe-group would keep returning an empty string, but when the script was launched from the CLI ec2-describe-group behaved normally.
After some poking around, I found this StackOverflow post which points out that most the environment variables your shell has aren’t available in a cronjob.
With that in mind, I tried adding JAVA_HOME as well as EC2_HOME to my crontab. Doing this is pretty straight forward, just add these two lines above any of your scheduled jobs:
Unfortunately, this still didn’t resolve the issue. On a whim, I decided to check what type of file ec2-describe-group actually is and discovered that its a Bash script not a Java JAR. Looking at the Bash, the file is actually just executing “EC2_HOME/bin/ec2-cmd DescribeGroups” but it utilizes other environment variables that my cron didn’t have.
For simplicity’s sake, I decided to just switch the PHP script to run ec2-cmd directly and finally everything started working as expected.
Posted In: Tips n' Tricks