Thursday, March 17, 2022

[SOLVED] How to run a bash script in a AWS CloudFormation template

Issue

I am trying to install MongoDB from a script in a EC2 from AWS CloudFormation. I want the script to automatically run when the stack is created from the template.

On line 303 of href="https://github.com/aws-quickstart/quickstart-mongodb/blob/main/templates/mongodb-node.template.yaml" rel="nofollow noreferrer">this template by Amazon you can see they do this

However, I am confused on the use of the backslash at every line. What format is needed to put a bash script into a AWS template so it runs on startup?


Solution

This is called a userdata and in CloudFormation (CFN) it can be specified in multiple ways. The template in the link also use cfn-ini thus it has those "backslash". They are used to split a single line into multiple lines for readability.

Often the following form of user-data is enough which is easier to write and read:

      UserData: !Base64
        Fn::Sub: |
          #!/bin/bash
          echo "first command in bash"
          echo "second command in bash"
          echo "and so on ..."     


Answered By - Marcin
Answer Checked By - Gilberto Lyons (WPSolving Admin)