Automatically Launch/Stop EC2 Instances Using Shells Script & AWS CLI

Automatically Launch Stop EC2 Instances Using Shell Script & AWS CLI


#How to start an EC2 instance:

Step 1: Install and configure AWS CLI if not done already. (If you missed that, Please refer my earlier post  / video https://tinyurl.com/yaf8dltr )

Step 2: Create a script file 'ec2startscript.sh'. I will recommend to create this file in root project directory path : /var/www/html

>> cd /var/www/html
>> touch ec2startscript.sh

Step 3: Get instance ids from AWS console which you want to start.

Step 4: Now open that file and add below code and save it.

>> nano ec2startscript.sh

Code:
#!/bin/bash
# Start EC2 Instance
aws ec2 start-instances --instance-ids pasteInstanceIdHere


#How to stop an EC2 instance:

Step 1: Create a script file 'ec2stopscript.sh'. I will recommend to create this file in root project directory path : /var/www/html

>> cd /var/www/html
>> touch ec2stopscript.sh

Step 2: Get instance id from AWS console which you want to start.

Step 3: Now open that file and add below code and save it.

>> nano ec2stopscript.sh

Code:
 #!/bin/bash
 # Stop EC2 Instance
aws ec2 stop-instances --instance-ids pasteInstanceIdHere

Note: Provide executable permission to shell script file ec2stopscript.sh

#How to provide public IP address to running EC2 instance:

Step 1: Create a script file 'ec2ipscript.sh'. I will recommend to create this file in root project directory path : /var/www/html

>> cd /var/www/html
>> touch ec2ipscript.sh

Step 2: Get instance id from AWS console which you want to start.

Step 3: Now open that file and add below code and save it.

>> nano ec2ipscript.sh

Code:
#!/bin/bash

stateArray=`sh ec2startscript.sh | grep "Name"`
IFS=':' read -a currentState <<< "$stateArray[1]"
stateString=${currentState[1]}
IFS='"' read -a state <<< "$stateString[1]"
while [ "${state[1]}" == "running" ]
do
    aws ec2 describe-instances | grep "PublicIpAddress"
    break
done

Happy Learning AWS Services!!!! :) Still Doubts? lets put your questions in below comment box! Thanks!


Watch Video:
Automatically Launch/Stop EC2 Instances Using Shells Script & AWS CLI Automatically Launch/Stop EC2 Instances Using Shells Script & AWS CLI Reviewed by Pranay Gondane on 3:32:00 AM Rating: 5

No comments

Free! Free!Free! Subscribe to Get Free PHP (Magento) tutorial Update in Your Inbox!!! Hurry Up!!!