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

Learn how to work with AWS EC2 using Shell Script.

No comments

Do you turn off off your lights when you leave your home or room ? Yes of course similarly when you don’t require any instance for sometime , its always a good practices to stop them and only start when required.

AWS EC2 is one of the most important and widely used service of Amazon where we launch instances. Many AWS accounts have almost multiple instance that are ideal and and requires some kind of automation to bring them either to stop state and when required power them on right away. Shell script works very well in automation world and for these activities . So Lets get started.

In this tutorial we will go through Shell script that takes few seconds to power on that is start or stop the instance.

Table of Content

  1. What is Shell script ?
  2. What is AWS EC2 instance?
  3. Prerequisites
  4. Install AWS CLI Version 2 on windows machine
  5. How to Start and Stop AWS EC2 instance in Amazon account using shell script
  6. Conclusion

What is Shell Scripting or Bash Scripting?

Shell Script is simply a text of file with various or lists of commands that are executed even on terminal or shell one by one. But in order to make thing little easier and run together as a group and in quick time we write them in single file and run it.

Main tasks which are performed by shell scripts are : file manipulation , printing text , program execution. We can include various environmental variables in script that can be used at multiple places , run programs and perform various activities are known as wrapper scripts.

A good shell script will have comments, preceded by a pound sign or hash mark, #, describing the steps. Also we can include conditions or pipe some commands to make more creative scripts.

When we 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 the top to the bottom.

What is AWS EC2 instance?

AWS EC2 stands for Amazon web service elastic compute cloud. AWS EC2 is just like a virtual server that is highly scalable in nature. The best part of EC2 instance is that, you don’t need to invest in any sort of hardware and it hardly takes few seconds to few minutes to launch. Once this is launched in few mins you are ready to deploy your applications. You can launch as many ec2 instance you wish to launch.

  • AWS EC2 service provides you Preconfigured templates known as AMI ( Amazon machine Image ) that includes operating system and software configurations that are highly required. Using these preconfigured templates you can launch your EC2 instances.
  • You can use Preconfigured templates and on the top of these templates you can configure your own software’s and data you wish to have when an instance is launched.
  • AWS EC2 service provides you various types of instance types with different CPU and Memory configurations. For Example: t2.micro, t2.medium etc.
  • AWS EC2 service provides login to these launched instances with completed security such as by creating a Key pair ( One of the key is public which remains with AWS and private is given the owner of instance)
  • AWS EC2 service allows you to add two kinds of storage . First storage is known as instance store volumes which are temporary storage and the other storage is EBS which is Elastic block storage & these are permanent storage.
  • Once AWS EC2 instance is launched you are the owner of the instance.
  • AWS EC2 is launched with root device volume that boots your system. You can have root device volumes as instance store based or as EBS based.
  • AWS EC2 service provides various states of a launched instance such as STOPPED , RUNNING , TERMINATED.
    • Note: Once instance is terminated it cannot be restarted back.

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. Python must be installed on windows machine which will be required by AWS cli. If you want to install python on windows machine follow here
  4. You must have Git bash already installed on your windows machine. If you don’t have install from here
  5. Code editor for writing the shell script on windows machine. I would recommend to use visual studio code on windows machine. If you wish to install visual studio on windows machine please find steps here

In this demo , we will use shell script to launch AWS IAM user. So In order to use shell scripts from your local machine that is windows you will require AWS CLI installed and configured. So First lets install AWS CLI and then configure it.

Install AWS CLI Version 2 on windows machine

  • Download the installed for AWS CLI on windows machine from here
  • Select I accept the terms and then click next button
  • Do custom setup like location of installation and then click next button
  • Now you are ready to install the AWS CLI 2
  • Click finish and now verify the AWS cli
  • Verify the AWS version by going to command prompt and type
aws --version

Now AWS cli version 2 is successfully installed on windows machine, now its time to configure AWS credentials so that our shell script connects AWS account and execute commands.

  • Configure AWS Credentials by running the command on command prompt
aws configure
  • Enter the details such as AWS Access key , ID , region . You can skip the output format as default.
  • Check the location on your system C:\Users\YOUR_USER\.aws file to confirm the the AWS credentials
  • Now, you’re AWS credentials are configured successfully.

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

Now we have configured AWS cli on windows machine , its time to create our shell script to stop and start ec2 instance.

This is a demo tutorial so we will show only one instance that will start if instance state is stopped and will stop it if its in running state.

  • Create a folder on your desktop and under that create file start-stop-ec2.sh
# /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
  • Now open visual studio code and open the location of file start-stop-ec2.sh and choose terminal as Bash
  • Now run the script
./start-stop-ec2.sh <Instance-ID>    # Provide the EC2 instance ID along with script
  • Script ran successfully , now lets verify the if EC2 instance has been stopped from running state by going on AWS account.
  • Great , Instance has been successfully stopped. Lets Now ,re- run the script to restart the instance
./start-stop-ec2.sh <Instance-ID>    # Provide the EC2 instance ID along with script

Conclusion

In this tutorial, we demonstrated what is  Amazon EC2 and learnt 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 it for AWS EC2 instances

Hope this tutorial will help you in understanding the shell script and working with AWS EC2 on Amazon cloud. Please share with your friends

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 )

Google photo

You are commenting using your Google 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