Free EC2 Scheduler to Start and Stop Instances Automatically in Ubuntu

Firstly, you have to install EC2 API Tools & AMI Tools.

Edit sudo nano /root/.bashrc and add following at the end.

export EC2_REGION=<your-ec2-region>
export EC2_URL=ec2.$EC2_REGION.amazonaws.com
export AWS_ACCESS_KEY=<your-access-key>
export AWS_SECRET_KEY=<your-secret-key>
export JAVA_HOME=/usr/lib/jvm/java-7-openjdk-amd64/jre

Remember to change <your-ec2-region>, <your-access-key>, <your-secret-key> accordingly.

Create sudo nano ~/start_instances.sh

# start_instances.sh

export EC2_REGION=<your-ec2-region>
export EC2_URL=ec2.$EC2_REGION.amazonaws.com
export AWS_ACCESS_KEY=<your-access-key>
export AWS_SECRET_KEY=<your-secret-key>
export JAVA_HOME=/usr/lib/jvm/java-7-openjdk-amd64/jre

ec2-start-instances <instance-id>
sleep 5

And create sudo nano ~/stop_instances.sh

# stop_instances.sh

export EC2_REGION=<your-ec2-region>
export EC2_URL=ec2.$EC2_REGION.amazonaws.com
export AWS_ACCESS_KEY=<your-access-key>
export AWS_SECRET_KEY=<your-secret-key>
export JAVA_HOME=/usr/lib/jvm/java-7-openjdk-amd64/jre

ec2-stop-instances <instance-id>
sleep 5

To add into cronjob, crontab -e

# monday to friday, morning 9am to start instances
0 8 * * 1-5 /bin/bash -c ~/start_instances.sh >> ~/start_instances.log 2>&1
# monday to friday, evening 5pm to stop instances
0 17 * * 1-5 /bin/bash -c ~/stop_instances.sh >> ~/stop_instances.log 2>&1

It will create a log file for start & stop instances.

That’s all for a Free and Simple EC2 Scheduler to start and stop instances automatically in your Ubuntu server.

You could also add a timestamp for your log files with this tutorial: Adding Timestamp Date Time while Saving a Log File from Crontab Cronjob Ubuntu Redhat Linux.

Adding Timestamp Date Time while Saving a Log File from Crontab Cronjob Ubuntu Redhat Linux

This is just a quick solution to put a timestamp with each line of the output of some command in Ubuntu Redhat Linux (*nix). It’s a very simple thing, thought I’d write it down here so maybe it’ll help somebody some day.

I have a cron job running on my server, it’s a high frequency job so I don’t want to send email reports each time, I’m logging it into a file, but I want to log the timestamp of each time it runs and logs something to this file, I didn’t want to change the code behind it to also print the timestamp with each write to the output, so I pipelined the command to a simple bash script that will append the timestamp to each line in the output then write the result to the stdout again.

Here is the bash script for sudo nano ~/timestamp.sh

#!/bin/bash
while read x; do
 echo -n `date +%d/%m/%Y\ %H:%M:%S`;
 echo -n " ";
 echo $x;
done

Then I edited the cron job crontab -e line to be like this:

* 9 * * 1-5 ~/my-cronjob-command.sh 2>&1 | ~/timestamp.sh >> /var/log/cron/my-cronjob-command.log

And you’re done!

Enjoy it.