AWS: Bash helper functions for common AWS CLI calls

The AWS CLI provides a comprehensive command set, but if you want advanced functionality such as checking if an object already exists before you create it, or polling an instance until it is a certain state then you will need a slightly higher level of abstraction.

My aws-common-funcs.sh script provides a set of Bash functions that conveniently wrap a subset of the more commonly used EC2 commands.  These functions only cover a subset of the EC2 entities.

Prerequisites

These functions use the AWS CLI, so you must ensure that the AWS CLI is first installed and configured.

Inclusion in Bash script

To get access to the functions, simply source aws-common-funcs.sh from your Bash script.  If your script and this one are in the same directory, you can include it like below:

BIN_DIR=$(dirname ${BASH_SOURCE[0]})
source $BIN_DIR/aws-common-funcs.sh

Function return values

Although Bash functions usually only return a number or echoed string as a return value, these functions instead use ‘eval’ at the end to put the return value back into a specified variable name.

As an example, if you want the current region value put into the variable named ‘$region’, use the ‘showRegion’ function like below:

showRegion "region"
echo "Region: $region"

Tagging

Most of the entities created have a tag named “Name” added so they are more easily viewed in the AWS console (which understands this tag), and can be searched for more conveniently.

Interpret empty return values

If a return value is empty it that typically means it was not found.

For example, let’s look for a VPC named “myvpc”.  The function ‘lookForVPC’ puts the return value into a variable named ‘vpcId’ which is then tested with ‘-z’ to understand if it was found or needs to be created.

vpcName="myvpc"

lookForVPC vpcId $vpcName
if [ -z $vpcId ]; then
  echo "VPC $vpcName not found, going to create"
  createVPC vpcId $vpcName "10.0.0.0/16" 
else
  echo "VPC $vpcName found, skipping creation"
fi

Example Usage

For examples of usage, see my aws-create-bosh-env.sh which exercises these utility methods.

Searching

  • lookForVPC
  • lookForSubnet
  • lookForSubnetAvailabilityField
  • lookForElasticIp
  • lookForElasticIPOnInstance
  • lookForKeyPair
  • lookForSecurityGroup
  • lookForInternetGateway
  • lookForNATGateway
  • lookForRoutingTable
  • lookForLatestImage
  • lookForRunningInstance

Creation

  • createVPC
  • createSubnet
  • createElasticIp
  • createKeyPair
  • createSecurityGroup
  • createInternetGateway
  • createNATGateway
  • createRoutingTable
  • createInstance

Association

  • associateElasticIPWithInstance

Polling

  • waitForState – wait for state on instance, instancestatus, or NAT gateway

 

REFERENCES

AWS CLI Reference