Crunchy
Crunchy

Reputation: 196

How to run a bash script in a AWS CloudFormation template

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?

Upvotes: 5

Views: 4148

Answers (2)

Shivam Anand
Shivam Anand

Reputation: 1611

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

Upvotes: 3

Marcin
Marcin

Reputation: 238995

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

Upvotes: 8

Related Questions