Home > database >  How to run a bash script in a AWS CloudFormation template
How to run a bash script in a AWS CloudFormation template

Time:03-17

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 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?

CodePudding user response:

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 ..."     

CodePudding user response:

In General, if you have a very long single line bash command you can split it into multiple lines using a \ for ease of reading.
Please refer this StackExchange link. The AWS Cloudformation template referred in the question uses similar concept. Since it was a single line command, they have made it multiline for readability.

For reader's information, if you are using CloudFormation/YAML and you have a multi-line in-line bash/python script you can refer the | operator link1 link2

  • Related