How to Start and Stop AWS EC2 instance in AWS account using Shell script

Are you spending unnecessary money in AWS Cloud by keeping unused AWS EC2 instances in running states? Why not stop the AWS EC2 instance and only start when required by running a single Shell Script?

Multiple AWS accounts contain dozens of AWS EC2 instances that require some form of automation to stop or start these instances, and to achieve this, nothing could be better than running a shell script.

In this tutorial, you will learn step by step how to Start and Stop AWS EC2 instance in AWS account using Shell script.

Still interested? Let’s dive in!

Join 28 other followers

Table of Content

  1. What is Shell Scripting or Bash Scripting?
  2. What is AWS EC2 instance?
  3. Prerequisites
  4. Building a shell script to start and stop AWS EC2 instance
  5. Executing the Shell Script to Stop AWS EC2 instance
  6. Verifying the Stopped AWS EC2 instance
  7. Executing the Shell Script to Start AWS EC2 instance
  8. Verifying the Running AWS EC2 instance
  9. Conclusion

What is Shell Scripting or Bash Scripting?

Shell Script is a text file containing lists of commands executed on the terminal or shell in one go in sequential order. Shell Script performs various important tasks such as file manipulation, printing text, program execution.

Shell script includes various environmental variables, comments, conditions, pipe commands, functions, etc., to make it more dynamic.

When you execute a shell script or function, a command interpreter goes through the ASCII text line-by-line, loop-by-loop, test-by-test, and executes each statement as each line is reached from top to bottom.

What is AWS EC2 instance?

AWS EC2 stands for Amazon web service elastic compute cloud. AWS EC2 is simply a virtual server that gets launched in quick time, and you don’t need to worry about the hardware. After the AWS EC2 instance is launched, you can deploy highly scalable and available applications.

There are some important components in AWS EC2 instance such as:

AWS EC2 AMI

  • AWS EC2 contains preconfigured templates known as AMI ( Amazon Machine Image ) that include an operating system and software configurations that are highly required. Using these preconfigured templates you can launch as many AWS EC2 instances.

You can configure your own software’s and data you wish to have when an instance on top of Preconfigured templates.

Amazon Machine Image template
Amazon Machine Image template

AWS EC2 instance type

AWS EC2 contains various AWS EC2 instance types with different CPU and memory configurations such as t2.micro, t2.medium, etc.

AWS EC2 instance type
AWS EC2 instance type

Amazon EC2 key pairs

AWS EC2 instance allows you to log in to these launched instances with complete security by creating a Keypair where one of the keys is public that remains within the AWS account, and another is the private key that remains with the owner of the instance.

AWS EC2 EBS Storage

AWS EC2 allows you to add two kinds of storage that is ec2 instance store volumes which are temporary storage, and Elastic block storage (AWS EBS), the permanent storage.

AWS EC2 is launched with root device volume ( ec2 instance store volumes or AWS EBS ) that allows you to boot the machine.

AWS EC2 EBS Storage
AWS EC2 EBS Storage

AWS EC2 instance state

AWS EC2 service provides various states of a launched instance such as stopped, started, running, terminated. Once the instance is terminated, it cannot be restarted back.

AWS EC2 instance state
AWS EC2 instance state

Prerequisites

  1. AWS account to create ec2 instance. If you don’t have AWS account please create from AWS account or AWS Account
  2. Windows 7 or plus edition where you will execute the shell script.
  3. AWS CLI installed. To install AWS CLI click here.
  4. Git bash. Yo install Git bash click here
  5. Code editor for writing the shell script on windows machine such as visual studio code. To install visual studio click here.

Building a shell script to start and stop AWS EC2 instance

Now that you have a good idea about the AWS EC2 instance and shell script but let’s learn how to build a shell script to start and stop the AWS EC2 instances.

  • Create a folder of your windows machine at any location. Further under the same folder create a file named start-stop-ec2.sh and copy/paste the below code.
# /usr/bin/bash 

set -e  # set -e stops the execution of a script if a command or pipeline has an error

id=$1   # Provide the instance ID with the name of the script

# Checking if Instance ID provided is correct 

function check_ec2_instance_id () {
    
    if echo "$1" | grep -E '^i-[a-zA-Z0-9]{8,}' > /dev/null; then 
           echo "Correct Instance ID provided , thank you"
           return 0
    else 
          echo "Opps !! Incorrect Instance ID provided !!"
          return 1
    fi
}

# Function to Start the instance 

function ec2_start_instance ()   {
     aws ec2 start-instances --instance-ids $1 
}

# Function to Stop the instance 

function ec2_stop_instance ()   {
     aws ec2 stop-instances --instance-ids $1 
}

# Function to Check the Status of the instance

function ec2_check_status ()   {
     aws ec2 describe-instances --instance-ids $1 --query "Reservations[].Instances[].State.Name" --output text
}

# Main Function 

function main ()  {
     check_ec2_instance_id $1                # First it checks the Instance ID
     echo " Instance ID provided is $1"  # Prints the message
     echo "Checking the status of $1"    # Prints the message
     ec2_check_status $1
                 # Checks the Status of Instance
   
     status=$(ec2_check_status $id)     # It stores the status of Instance
     if [ "$status" = "running" ]; then     
         echo "I am stopping the instance now"
         ec2_stop_instance $1
         echo "Instance has been stopped successfully"
     else 
         echo "I am starting the instance now"
         ec2_start_instance $1
         echo "Instance has been Started successfully" 
     fi

}

main $1                                 # Actual Script starts from main function

Executing the Shell Script to Stop AWS EC2 instance

Previously you created the shell script to start and stop the AWS EC2 instance, which is great; but it is not doing much unless you run it. Let’s execute the shell script now.

  • Open the visual studio code and then open the location of file start-stop-ec2.sh.
Opening Shell script on visual studio code
Opening Shell script on visual studio code
  • Finally execute the shell script.
./start-stop-ec2.sh <Instance-ID>    # Provide the EC2 instance ID along with script
Executing the shell script to stop the AWS Ec2 instance
Executing the shell script to stop the AWS Ec2 instance

Verifying the Stopped AWS EC2 instance

Earlier in the previous section, the shell script ran successfully; let’s verify the if AWS EC2 instance has been stopped from running state in the AWS account.

  • Open your favorite web browser and navigate to the AWS Management Console and log in.
  • While in the Console, click on the search bar at the top, search for ‘EC2’, and click on the EC2 menu item and you should see the instance you specified in shell script has stopped now.
Viewing the stopped AWS EC2 instance
Viewing the stopped AWS EC2 instance

Executing the Shell Script to Start AWS EC2 instance

Now thaYouuccessfully stopped and verified the AWS EC2 instance in the AWS cloud. This time let’s restart the instance using the same script.

./start-stop-ec2.sh <Instance-ID>    # Provide the EC2 instance ID along with script
Executing the shell script to start the instance
Executing the shell script to start the instance

Verifying the Running AWS EC2 instance

Similarly, in this section, let’s verify the if AWS EC2 instance has been restarted successfully in the AWS account.

Viewing the running AWS EC2 instance
Viewing the running AWS EC2 instance

Conclusion

In this tutorial, you learned what is Amazon EC2 and learned how to start or stop AWS EC2 using shell script on AWS step by step. It is always a good practice to turn off your lights when you leave your home or room, similarly do for EC2 instances.

So which AWS EC2 instance are you planning to stop going further and save dollars?

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s