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.

Install EC2 API AMI Tools in Ubuntu

ec2-api-tools and ec2-ami-tools are available in multiverse. The
multiverse component is not enabled in /etc/apt/sources.list by default in
the Ubuntu ec2 images.

There are 2 ways to get at these:

a) get (older) versions released with karmic by adding multiverse to
/etc/apt/sources.list:

$ sudo sed -i.dist 's,universe$,universe multiverse,' /etc/apt/sources.list
$ sudo apt-get update
$ sudo apt-get install ec2-api-tools ec2-ami-tools

b) add most recent versions backported to karmic:
Add the ppa https://launchpad.net/~ubuntu-on-ec2/+archive/ppa
Follow the instructions there, or:

$ sudo apt-get update && sudo apt-get install python-software-properties
$ sudo add-apt-repository ppa:ubuntu-on-ec2/ec2-tools
$ sudo apt-get update && sudo apt-get install ec2-api-tools ec2-ami-tools

That’s it. Enjoy your EC2 API Tools and EC2 AMI Tools in Ubuntu.