July 17, 2020 / Nirav S
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.
Connect to EC2 Instance via SSH or putty
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.
Have queries about your AWS project ideas and concepts? Please drop in your project details to discuss with our AWS experts, professionals and consultants.