Shell Script has different ouput via cron vs when run Manually

Hello Lads,

I deployed a script on my mac to start and stop EC2 instances on AWS console. The script when started manually on the terminal does the expected stop and start. Problem is when i try to schedule it on a cron, it fails to recognize the AWS Keys which i set up as ENV variable by adding them to ~/ .bash_profile and throws an error of missing key.

Note that when i do printenv on terminal i can see the AWS ENV variables. I can also see them when i cat the ~/ .bash_profile file. Can any one advise on what's happening here. All other crons on my mac are working fine.

# Run Daily to Start and Stop EC2 Instances
48 15 * * 1-5 /home/Dir/Documents/Scripts/BashScripts/start-ec2.sh >> /home/Dir/Documents/Scripts/BashScripts/CronStart.txt 
45 15 * * 1-5 /home/Dir/Documents/Scripts/BashScripts/stop-ec2.sh >> /home/Dir/Documents/Scripts/BashScripts/CronStop.txt
#!/bin/bash
export PATH=$PATH:/home/Dir
export AWS_ACCESS_KEY_ID
export AWS_SECRET_ACCESS_KEY
export AWS_CREDENTIAL_FILE

/usr/local/bin/ec2-stop-instances i-xxxx --region us-west-2
/usr/local/bin/ec2-stop-instances i-xxxx --region us-west-2

Output When Starting Manually. 

./start-ec2.sh 
INSTANCE	i-xxxx	stopped	pending
INSTANCE	i-xxxx	stopped	pending

Full Error which i capture in /var/Mail/Maddy
Subject: Cron /Users/Maddy/Documents/Scripts/BashScripts/stop-ec2.sh >> /Users/Maddy/Documents/Scripts/BashScripts/CronStop.txt
X-Cron-Env: <SHELL=/bin/sh>
X-Cron-Env: <PATH=/usr/bin:/bin>
X-Cron-Env: <LOGNAME=Maddy>
X-Cron-Env: <USER=Maddy>
X-Cron-Env: <HOME=/Users/Maddy>
Date: Tue, 14 Jun 2016 16:58:03 -0400 (EDT)

Required option '-O, --aws-access-key KEY' missing (-h for usage)
Required option '-O, --aws-access-key KEY' missing (-h for usage)

My Path Variable.
echo $PATH
/Library/Frameworks/Python.framework/Versions/3.4/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin
#!/bin/bash
export PATH=$PATH:/home/Dir
export AWS_ACCESS_KEY_ID
export AWS_SECRET_ACCESS_KEY
export AWS_CREDENTIAL_FILE

/usr/local/bin/ec2-stop-instances i-xxxx --region us-west-2
/usr/local/bin/ec2-stop-instances i-xxxx --region us-west-2

How does cron know that it is supposed to source your ~/.bash_profile?
You are exporting variables that might not have any value assigned to it, when it runs as a cronjob.
Assign the values you have in ~/.bash_profile or source your ~/.bash_profile.

1 Like