5

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?

3
  • @Marcin actually ive beens struggling. I am starting simple with this and its saying "Invalid template property or properties [Properties]" Commented Mar 17, 2022 at 5:50
  • 1
    Please make new question for the new issue. Commented Mar 17, 2022 at 6:04
  • @Marcin No problem. I have made a new post. Please check it out. Thank you! Commented Mar 17, 2022 at 7:18

2 Answers 2

8

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 ..."     
Sign up to request clarification or add additional context in comments.

1 Comment

Can you show a complete example of substitution within CloudFormation? This is actually hard as it seems to expect type "string."
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.