Blog History

December 29, 2020

AWS EC2 Stop/Start BASH script for end users to run on Linux or Mac

You must first provision an IAM user with permissions to perform the action:

{
    "Version""2012-10-17",
    "Statement": [
        {
            "Effect""Allow",
            "Action": [
                "ec2:StartInstances",
                "ec2:StopInstances",
            ],
            "Resource": [
                "arn:aws:ec2:us-east-1:<account number>:instance/i-1234567890"
            ]
        }
    ]
}

Configure the AWS CLI with the above IAM user on the end users local computer.

When they run the script, they will need to specify one of three options: status, start, or stop 

If writing this script in Windows, and trying to test in WSL or an actual Unix based system, then you might get this error:

'\r'command not found

Use "dos2unix" on the script file after each edit to modify the newline characters so they are Unix compatible [1].

Modified from source [2]

#!/bin/bash

INSTANCE_ID="i-1234567890"

function _log(){
    trailbefore=$2
    start=""
    if [ -z $trailbefore ] || [ $trailbefore = true ]
        then
        start=" - "
    fi

    printf "$start$1"
}

function run_command (){
    COMMAND=$1
    # note in the original parameter count as new parameter
    QUERY="$2 $3"
    OUTPUT="--output text"
    local result=$(eval aws ec2 $COMMAND --instance-ids $INSTANCE_ID $QUERY $OUTPUT)
    echo "$result"
}

function getStatus(){
    CMD="describe-instances"
    EXTRA="--query \"Reservations[].Instances[].State[].Name\""
    result=$(run_command $CMD $EXTRA)
    echo $result
}

function _checkStatus(){
    status=$(getStatus)
    if [ $status = "pending" ] || [ $status = "stopping" ]
        then
        _log "Current status: $status"
        _log " Wating "
        while [ $status = "pending" ] || [ $status = "stopping" ]
            do
            sleep 5
            _log "." false
            status=$(getStatus)
        done
        _log "\n" false
    fi
}

function start {
    CMD="start-instances"
    _checkStatus
    result=$(run_command $CMD)
    echo $result
}
function stop {
    CMD="stop-instances"
    _checkStatus
    result=$(run_command $CMD)
    echo $result
}

if [ -z "$1" ]
    then
    _log "\n Possible commands: status|start|stop \n\n"
else
    if [ $1 = "start" ] 
        then
        start
    elif [ $1 = "stop" ] 
        then
        stop
    elif [ $1 = "status" ] 
        then
        getStatus   
    fi
fi

[1] https://stackoverflow.com/questions/11616835/r-command-not-found-bashrc-bash-profile

[2] https://stackoverflow.com/questions/42641970/aws-cli-bash-script-to-manage-instances


 

No comments:

Post a Comment