6

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?

Crunchy
  • 186
  • 10
  • @Marcin actually ive beens struggling. I am starting simple with [this](https://ibb.co/rpgdkDt) and its saying "Invalid template property or properties [Properties]" – Crunchy Mar 17 '22 at 05:50
  • 1
    Please make new question for the new issue. – Marcin Mar 17 '22 at 06:04
  • @Marcin No problem. I have made a [new post](https://stackoverflow.com/questions/71508353/aws-cloudformation-template-not-accepting-bash-script). Please check it out. Thank you! – Crunchy Mar 17 '22 at 07:18

2 Answers2

7

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 ..."     
Marcin
  • 215,873
  • 14
  • 235
  • 294
  • Can you show a complete example of substitution within CloudFormation? This is actually hard as it seems to expect type "string." – rjurney Aug 02 '23 at 23:54
3

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

Shivam Anand
  • 952
  • 1
  • 10
  • 21