Learning how to execute a Bash script from CloudFormation

For those learning AWS/AWS CLI, CloudFormation is a tool for building infrastructure with AWS.

Here is a very simple document on how to use CloudFormation to build an AWS EC2 Linux instance and execute a bash script from CloudFormation against the newly created Linux instance. This is a counterpart document to Learning how to execute a Bash script from Terraform.

Executing a bash script from CloudFormation can be used to configure the newly created server or for any other purpose.

The example below will show how to execute a script named setup-lnxcfg-user; this bash script will prepare the newly created Linux instance for Ansible playbook execution from an Ansible controller server. The script creates a new login id named lnxcfg, sets up ssh-keys, and sudo access on the new instance. This instance will be an Ansible client of an Ansible controller server; using Ansible is beyond the scope of this document, however, learning how to execute a bash script from CloudFormation will be very useful.

The setup-lnxcfg-user bash script is as follows:

setup-lnxcfg-user:

The CloudFormation configuration file is below as example.yml.

A CloudFormation template can have arguments passed to the template via the ParameterKey and ParameterValue arguments. Within the Parameters section of the template, default values can be assigned for each parameter. Arguments not passed to the template will become the default value if a default value has been defined. Those arguments that are passed to the template override any default value.

Within the CloudFormation code below there is a parameter named UserData. The UserData can be used to pass the bash script which needs to be encoded as base64 data to CloudFormation. We can do this by passing a parameter:

base64 above is a Linux command which will encode/decode data and print to the Linux standard output. The -w option is to wrap encoded lines after the cols character (default 76). Using zero (as in -w0) will disable line wrapping of the setup-lnxcfg-user bash script. Using the syntax from above the parameter UserData will now have the value of the bash script which has been encoded as base64.

After the server is finished provisioning and the bash script has been executed an Ansible controller server will be able connect to the new Linux instance using the lnxcfg userid and configure the new instance.

example.yml CloudFormation:

To execute the CloudFormation from a Linux command line with the AWS CLI installed execute:

To execute the CloudFormation from a Linux command line and override all the parameters along with the UserData parameter execute:

Executing a bash script from CloudFormation can be a very easy and useful.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store