July 17, 2020 / Nirav Shah
Do you want to know, how to start and stop instance with a bash script?
Note This script and method will work only if your both EC2 Instances are within the same VPC, same Region and same AWS account.
Step 1
Connect to EC2 Instance via SSH or putty
Step 2
Create Two Script files , start and stop script at any location. Let say I am creating them in /root directory.
Use Vi or Nano editor to create or edit the files.
$ nano /root/ec2instance_start.sh
Add the following lines in the start script and save and exit using Ctrl+O and Ctrl+ x command.
#! /bin/bash aws ec2 start-instances –instance-ids i-f0c3678r3dba65876 $ nano /root/ec2instance_stop.sh
Add the following lines in the stop script and save and exit using Ctrl+O and Ctrl+ x command.
#! /bin/bash aws ec2 stop-instances –instance-ids i-f0c3678r3dba65876
Step 3 Make the scripts executable
To make both the scripts executable run following commands.
$ chmod +x /root/ec2instance_start.sh $ chmod +x /root/ec2instance_stop.sh
Step 4 Schedule the Stop and Start using Cronjob.
Run the following command to edit your Cron job.
$ crontab -e
Add the following line to start and stop the instance at 11 AM and 7 PM respectively.
00 11 * * * sh /root/ec2instance_start.sh > /tmp/ec2instance_start.log 00 19 * * * sh /root/ec2instance_stop.sh > /tmp/ec2instance_stop.log
Once everything shown as above is done, the EC2 instance will start and stop at the above mentioned time.
Also Read: How to Connect an AWS Windows EC2 Instance
FAQs:
As a Director of Eternal Web Private Ltd an AWS consulting partner company, Nirav is responsible for its operations. AWS, cloud-computing and digital transformation are some of his favorite topics to talk about. His key focus is to help enterprises adopt technology, to solve their business problem with the right cloud solutions.
Have queries about your project idea or concept? Please drop in your project details to discuss with our AWS Global Cloud Infrastructure service specialists and consultants.