Start and Stop EC2 instance using Bashscript

Start and Stop EC2 instance using Bashscript

July 17, 2020 / Nirav Shah

Do you want to know, how to start and stop instance with a bash script?

Steps To Start And Stop EC2 Instance Using Bashscrip

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:

  1. What is an EC2 Instance?
  2. How to stop and start AWS EC2 instance automatically?
  3. How many instances can I run in Amazon EC2?

Talk to AWS Certified Consultant

    Spread Love By Sharing:

    Let’s Talk About Your Needed AWS Infrastructure Management Services

    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.

    • Swift Hiring and Onboarding
    • Experienced and Trained AWS Team
    • Quality Consulting and Programming
    Let’s Connect and Discuss Your Project