Skip to content

Commit

Permalink
Draft of new EC2 Instance Type Change CLI example
Browse files Browse the repository at this point in the history
  • Loading branch information
bisdavid committed Mar 2, 2020
1 parent 0fa6d25 commit c9fc1e1
Show file tree
Hide file tree
Showing 4 changed files with 74 additions and 73 deletions.
34 changes: 17 additions & 17 deletions aws-cli/bash-linux/ec2/change-ec2-instance-type/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,21 +13,21 @@ specific language governing permissions and limitations under the License.
# Change Amazon EC2 Instance Type

This example demonstrates how to change the instance type of an Amazon EC2
instance type. It stops the instance if it is running, changes the instance
type, then, if requested, restarts the instance.
instance. It stops the instance if it's running, changes the instance type,
and then, if requested, restarts the instance.

## Files
* change_ec2_instance_type.sh - main script example file
* test_change_ec2_instance_type.sh - unit/integration test file
* general.sh - common test support function file

## Purpose
The main script file contains the function `change_ec2_instance_type()` that perform the following tasks:
The main script file contains the `change_ec2_instance_type()` function that perform the following tasks:

* Verifies that the specified EC2 instance exists.
* Warns the user (unless -f was selected) before stopping the instance.
* Changes the instance type.
* If requested (by selecting -r), restarts the instance and confirms that the instance is running.
* Verifies that the specified EC2 instance exists
* Warns the user (unless -f was selected) before stopping the instance
* Changes the instance type
* If requested (by selecting -r), restarts the instance and confirms that the instance is running

## Prerequisites

Expand All @@ -36,7 +36,7 @@ The main script file contains the function `change_ec2_instance_type()` that per
* A running EC2 instance in the account for which you have permission to stop and modify. If you run the test script, it launches an instance for you, tests changing the type, and then terminates the instance.

## Running the Code
This example is written as a function in a shell script file (*`change_ec2_instance_type.sh`*) that you can `source` from another script or from the command line. Once the function is in memory, you can invoke it from the command line. For example, the following commands change type of the specified instance to `t2.nano`:
This example is written as a function in a shell script file (*`change_ec2_instance_type.sh`*) that you can `source` from another script or from the command line. Once the function is in memory, you can invoke it from the command line. For example, the following commands change the type of the specified instance to `t2.nano`:

```
source ./change_ec2_instance_type.sh
Expand All @@ -45,29 +45,29 @@ source ./change_ec2_instance_type.sh

## Parameters

**-i** *(string)* Specifies the instance ID to modify.
**-i** - *(string)* Specifies the instance ID to modify.

**-t** *(string)* Specifies the EC2 instance type to switch to.
**-t** - *(string)* Specifies the EC2 instance type to switch to.

**-r** *(switch)* If set, the function restarts the instance after the type switch. Default: the function doesn't restart the instance.
**-r** - *(switch)* If set, the function restarts the instance after the type switch. Default: the function doesn't restart the instance.

**-f** *(switch)* If set, the function doesn't prompt the user before shutting down the instance to make the type switch. Default: the script prompts the user to confirm shutting down the instance before making the switch.
**-f** - *(switch)* If set, the function doesn't prompt the user before shutting down the instance to make the type switch. Default: the script prompts the user to confirm shutting down the instance before making the switch.

**-v** *(switch)* If set, the function displays status throughout its operation. Default: the script operates silently and displays output only in the event of an error.
**-v** - *(switch)* If set, the function displays status throughout its operation. Default: the script operates silently and displays output only in the event of an error.

## Testing the example
## Testing the Example
The file *change_ec2_instance_type_test.sh* script tests the various code paths for the `change_ec2_instance_type` function.

If all steps in the test script work correctly, the test script removes all resources that it created.

You can run the test script with the following parameters:

**-v** *(switch)* The tests each show a pass/failure status as they run. Default: the tests runs silently and the output includes only the final overall pass/failure status.
**-v** - *(switch)* The tests each show a pass/failure status as they run. Default: the tests runs silently and the output includes only the final overall pass/failure status.

**-i** *(switch)* The script pauses after each test to enable you to browse the intermediate results of each step. When run this way, you can examine the current status of the instance using the Amazon EC2 console. The script proceeds to the next step after you press *ENTER* at the prompt.
**-i** - *(switch)* The script pauses after each test to enable you to browse the intermediate results of each step. When run this way, you can examine the current status of the instance using the Amazon EC2 console. The script proceeds to the next step after you press *ENTER* at the prompt.

## Additional Information

* As an AWS best practice, grant this code least privilege, or only the permissions required to perform a task. For more information, see [Grant Least Privilege](https://docs.aws.amazon.com/IAM/latest/UserGuide/best-practices.html#grant-least-privilege) in the _AWS Identity and Access Management (IAM) User Guide_.
* This code has not been tested in all AWS Regions. Some AWS services are available only in specific Regions. For more information, see [Service Endpoints and Quotas](https://docs.aws.amazon.com/general/latest/gr/aws-service-information.html) in the _AWS General Reference Guide_.
* Running this code can result in charges to your AWS account. It is your responsibility to ensure that any resources created by this script are removed when you are done with them.
* Running this code can result in charges to your AWS account. It's your responsibility to ensure that any resources created by this script are removed when you are done with them.
32 changes: 17 additions & 15 deletions aws-cli/bash-linux/ec2/change-ec2-instance-type/awsdocs_general.sh
Original file line number Diff line number Diff line change
Expand Up @@ -11,13 +11,13 @@
# specific language governing permissions and limitations under the License.
###############################################################################
#
# This script contains general purpose functions that are used throughout
# the AWS Command Line Interface (AWS CLI) code samples that are maintained
# in the repo at https://github.com/awsdocs/aws-doc-sdk-examples
# This script contains general-purpose functions that are used throughout
# the AWS Command Line Interface (AWS CLI) code examples that are maintained
# in the repo at https://github.com/awsdocs/aws-doc-sdk-examples.
#
# They are intended to abstract functionality that is required for the tests
# to work without cluttering up the code. The intent is to ensure the purpose
# of the code is clear.
# to work without cluttering up the code. The intent is to ensure that the
# purpose of the code is clear.

# Set global defaults:
VERBOSE=false
Expand Down Expand Up @@ -46,7 +46,7 @@ function run_test {
test_failed "The test \"$DESCRIPTION\" returned an unexpected error code: $ERR"
fi

#now check the error message, if we provided other than "".
# Now check the error message, if we provided other than "".
if [[ -n "$EXPECTED_OUTPUT" ]]; then
MATCH=$(echo "$RESPONSE" | grep "$EXPECTED_OUTPUT")
# If there was no match (it's an empty string), then fail.
Expand All @@ -72,13 +72,13 @@ function test_failed {
errecho "===TEST FAILED==="
errecho "$@"
errecho ""
errecho " One or more of the tests failed to complete successfully. This means that any"
errecho " tests after the one that failed test didn't run and might have left resources"
errecho " One or more of the tests failed to complete successfully. This means that"
errecho " any tests after the one that failed didn't run and might have left resources"
errecho " still active in your account."
errecho ""
errecho "IMPORTANT:"
errecho " Resources created by this script can incur charges to your AWS account. If the"
errecho " script did not complete successfully, then you must review and manually delete"
errecho " script didn't complete successfully, then you must review and manually delete"
errecho " any resources created by this script that were not automatically removed."
errecho ""
exit 1
Expand Down Expand Up @@ -118,30 +118,32 @@ function ipause {
fi
}

# Initialize the shell's RANDOM variable
# Initialize the shell's RANDOM variable.
RANDOM=$$
###############################################################################
# function generate_random_name
#
# This function generates a random file name with using the specified root
# This function generates a random file name with using the specified root,
# followed by 4 groups that each have 4 digits.
# The default root name is "test"
# The default root name is "test".
###############################################################################
function generate_random_name {

ROOTNAME="test"
if [[ -n $1 ]]; then
ROOTNAME=$1
fi

# Initialize the filename variable
# Initialize the FILENAME variable
FILENAME="$ROOTNAME"
# Configure random number generator to issue numbers between 1000 and 9999, inclusive
# Configure random number generator to issue numbers between 1000 and 9999,
# inclusive.
DIFF=$((9999-1000+1))

for _ in {1..4}
do
rnd=$(($((RANDOM%DIFF))+X))
# make sure that the number is 4 digits long
# Make sure that the number is 4 digits long.
while [ "${#rnd}" -lt 4 ]; do rnd="0$rnd"; done
FILENAME+="-$rnd"
done
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@
# -f [switch, optional] If set, the function doesn't pause and ask before
# stopping the instance.
# -r [switch, optional] If set, the function restarts the instance after
# after changing the type.
# changing the type.
# -h [switch, optional] Displays this help.
#
# Example:
Expand All @@ -39,7 +39,7 @@
# 1 if it fails
###############################################################################

# Import the general purpose functions
# Import the general_purpose functions.
source awsdocs_general.sh

###############################################################################
Expand All @@ -57,15 +57,15 @@ source awsdocs_general.sh
# 1 if the instance doesn't exist
# AND:
# Sets two global variables:
# EXISTING_STATE contains the running/stopped state of the instance.
# EXISTING_TYPE contains the current type of the instance.
# EXISTING_STATE - Contains the running/stopped state of the instance.
# EXISTING_TYPE - Contains the current type of the instance.
###############################################################################
function get_instance_info {

# Declare local variables.
local INSTANCE_ID RESPONSE

# This function accepts a single parameter: the Instance ID.
# This function accepts a single parameter.
INSTANCE_ID=$1

# The following --filters parameter causes server-side filtering to limit
Expand All @@ -84,7 +84,7 @@ function get_instance_info {
return 1 # 1 in Bash script means error/false
fi

# If we got a response then the instance exists.
# If we got a response, the instance exists.
# Retrieve the values of interest and set them as global variables.
EXISTING_STATE=$(echo "$RESPONSE" | cut -f 1 )
EXISTING_TYPE=$(echo "$RESPONSE" | cut -f 2 )
Expand All @@ -104,7 +104,7 @@ function change_ec2_instance_type {
echo ""
echo "This function changes the instance type of the specified instance."
echo "Parameter:"
echo " -i Specify the instance id whose type you want to modify."
echo " -i Specify the instance ID whose type you want to modify."
echo " -t Specify the instance type to convert the instance to."
echo " -d If the instance was originally running, this option prevents"
echo " automatically restarting the instance."
Expand All @@ -114,17 +114,16 @@ function change_ec2_instance_type {
)

local FORCE RESTART REQUESTED_TYPE INSTANCE_ID VERBOSE OPTION RESPONSE ANSWER
local OPTIND OPTARG # Required to use getopts command in a function
#global EXISTING_TYPE EXISTING_STATE # These come from/to calling script

local OPTIND OPTARG # Required to use getopts command in a function.

# Set default values.
FORCE=false
RESTART=false
REQUESTED_TYPE=""
INSTANCE_ID=""
VERBOSE=false

# Retrieve the calling parameters
# Retrieve the calling parameters.
while getopts "i:t:frvh" OPTION; do
case "${OPTION}"
in
Expand All @@ -139,7 +138,7 @@ function change_ec2_instance_type {
done

if [[ -z "$INSTANCE_ID" ]]; then
errecho "ERROR: You must provide an instance id with the -i parameter."
errecho "ERROR: You must provide an instance ID with the -i parameter."
usage
return 1
fi
Expand All @@ -161,14 +160,14 @@ function change_ec2_instance_type {
# Check that the specified instance exists.
iecho -n "Confirming that instance $INSTANCE_ID exists..."
get_instance_info "$INSTANCE_ID"
# The function returns an error code <> 0 if the instance doesn't exist.
# If the instance doesn't exist, the function returns an error code <> 0.
if [[ ${?} -ne 0 ]]; then
errecho "ERROR: I can't find the instance \"$INSTANCE_ID\" in the current AWS account."
return 1
fi
# Function get_instance_info has returned two global values:
# $EXISTING_TYPE -- the instance type of the specified instance
# $EXISTING_STATE -- whether the specified instance is running
# $EXISTING_TYPE -- The instance type of the specified instance
# $EXISTING_STATE -- Whether the specified instance is running

iecho "confirmed $INSTANCE_ID exists."
iecho " Current type: $EXISTING_TYPE"
Expand All @@ -185,7 +184,7 @@ function change_ec2_instance_type {
if [[ "$EXISTING_STATE" == "running" ]]; then
# If it is, we need to stop it.
# Do we have permission to stop it?
# If -f (FORCE) was set, then we do.
# If -f (FORCE) was set, we do.
# If not, we need to ask the user.
if [[ $FORCE == false ]]; then
while true; do
Expand Down Expand Up @@ -221,7 +220,7 @@ function change_ec2_instance_type {
iecho "Instance is not in running state, so not requesting a stop."
fi;

# wait until stopped
# Wait until stopped.
iecho "Waiting for $INSTANCE_ID to report 'stopped' state..."
aws ec2 wait instance-stopped \
--instance-ids "$INSTANCE_ID"
Expand All @@ -231,7 +230,7 @@ function change_ec2_instance_type {
fi
iecho "stopped.\n"

# change the type - command produces no output
# Change the type - command produces no output.
iecho "Attempting to change type from $EXISTING_TYPE to $REQUESTED_TYPE..."
RESPONSE=$(aws ec2 modify-instance-attribute \
--instance-id "$INSTANCE_ID" \
Expand Down
Loading

0 comments on commit c9fc1e1

Please sign in to comment.