简体   繁体   English

如何在 AWS CloudFormation 模板中运行 bash 脚本

[英]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.我正在尝试从 AWS CloudFormation 的 EC2 中的脚本安装 MongoDB。 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在亚马逊的这个模板的第 303 行,你可以看到他们这样做

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?将 bash 脚本放入 AWS 模板以便它在启动时运行需要什么格式?

This is called a userdata and in CloudFormation (CFN) it can be specified in multiple ways.这称为用户数据,在CloudFormation (CFN) 中可以通过多种方式指定。 The template in the link also use cfn-ini thus it has those "backslash".链接中的模板也使用cfn-ini ,因此它有那些“反斜杠”。 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 ..."     

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.一般来说,如果你有一个很长的单行 bash 命令,你可以使用\将它分成多行以便于阅读。
Please refer this StackExchange link.请参考StackExchange 链接。 The AWS Cloudformation template referred in the question uses similar concept.问题中提到的 AWS Cloudformation 模板使用类似的概念。 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 |对于读者的信息,如果您正在使用 CloudFormation/YAML 并且您有一个多行内联bash/python 脚本,您可以参考| operator link1 link2运营商link1 link2

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM