Bash – AWS API Tools “Command Not Found” When Executing from Cron

amazon-web-servicesbashcron

I have created this bash script to generate a snapshot of my EBS Volume

#! /usr/bin/bash
ec2-create-snapshot -d "My Snapshot" vol-XXXXXXX -O <MyKey> -W <MyOtherKey>

And it works when I run this line in terminal, while connected to the server

bash myscript.sh

Then I created this crontab

PATH=/bin:/home/usr/bin/bash:/usr/bin/bash
0 * * * * (bash ~/../bash/myscript.sh)

#ALSO TRIED THESE LINES
#0 * * * * ~/../bash/myscript.sh
#0 * * * * (/usr/bin/bash ~/../bash/myscript.sh) 

And I get this message in my email

/home/ec2-user/../bash/myscript.sh: line 4: ec2-create-snapshot: command not found

I'm out of ideas about how to make this work. The problem seems to be that when executed from the crontab, the script is not finding the AWS API Tools.

Any ideas would be very appreciated.


For clarity, here is what ended up working. Thanks for pointing me in the right direction.

Connect to the server and then type echo $EC2_HOME and hit enter.

Then type echo $JAVA_HOME and hit enter.

Then type sudo find / -name "ec2-create-snapshot" (this one might return multiple values)

Make a note of the values that each of these return. You will use them in a minute.

Create this bash script:

#! /usr/bin/bash
export EC2_HOME=/your/ec2_home/path
export JAVA_HOME=/your/java_home/path

# Create an AWS Snapshot
/path/to/your/ec2-create-snapshot -d "Your Snapshot Description" vol-yourvolid -O YOURPUBLICKEY -W YOURPRIVATEKEY

You should be able to execute this by typing bash yourscriptname.sh into the terminal

Then open your cron with contab -e and add this line:

* * * * * (bash ~/your/dir/yourscriptname.sh) #CREATE AWS Snapshot

Hope this helps someone.

Best Answer

In addition to specifying the full path to the command as @ceejayoz says in the comments, you'll also need to set EC2_HOME to point to your EC2 tools directory, and you may also need to add $EC2_HOME/bin to your PATH in order for referenced files in the command scripts to be picked up correctly.

Rather than specifying a bunch of environment variables in your crontab, it's neater and more reliable to create a shell script that sets the environment and calls your command, and then call the script from your crontab.