【问题标题】:AWS CloudFormation userdata passingAWS CloudFormation 用户数据传递
【发布时间】:2017-10-21 13:16:42
【问题描述】:

如何将参数输入数据传递给 AWS cloudformation 中的 userdata。 示例:我有一个参数 EnvType,我将在运行 CFT 时将“qa”作为输入传递给该参数。我希望读取此参数值“qa”并将其传递给 userdata,以便我可以将其写入实例磁盘。

Parameters: {
    "EnvType": {
        "Description": "Environment type",
        "Type": "String",
        "AllowedValues": [
            "prod",
            "qa"
        ]
    }

我尝试在用户数据中使用它:

export STACK_TYPE='",
{
"Ref": "EnvType"
},
"'\n",
"echo \"$STACK_TYPE\" > stacktypes\n

我想将 EnvType 的这个输入附加到实例中名为 stacktypes 的文件中。

【问题讨论】:

    标签: amazon-web-services amazon-cloudformation


    【解决方案1】:

    您必须使用 Fn::Join 将用户数据字符串与来自 CloudFormation 的其他内在函数(例如 Ref)的结果实际“连接”起来。这是如何完成的示例:

    ...  
      "MyInstance": {
        "Type": "AWS::EC2::Instance",
        "Properties": {
          "UserData": {
            "Fn::Base64": {
              "Fn::Join": [
                "",
                [
                  "#cloud-config\n\nrepo_upgrade: all\n\n\nwrite_files:\n- path: /root/init.sh\n  owner: root:root\n  permissions: '0755'\n  content: |\n    #!/bin/bash\n\n    EC2_INSTANCE_ID=`wget -q -O - http://169.254.169.254/latest/meta-data/instance-id`\n    aws cloudformation signal-resource --stack-name ",
                  {
                    "Ref": "AWS::StackName"
                  },
                  " --status SUCCESS --logical-resource-id AutoScalingGroup --unique-id $EC2_INSTANCE_ID --region ",
                  {
                    "Ref": "AWS::Region"
                  }
                ]
              ]
            }
          }
          ...
        }
      }
    ...
    

    这可能是一项乏味的任务,我们在内部开发了一个工具来处理 UserData 的生成,但我知道有一些开源工具可以提供帮助(例如:https://github.com/cloudtools/troposphere)。

    【讨论】:

      【解决方案2】:

      您可以将堆栈参数传递/附加到实例中的文件中。 如果你有这样的参数,

      Parameters: {
      "EnvType": {
          ...
      }
      

      您可以尝试将下面的 UserData 添加到您的实例属性中。

         "Properties": {
            ...
            "UserData": {
              "Fn::Base64": {
                "Fn::Join": [
                  "",
                  [
                    "#!/bin/bash -xe\",
                    "echo ",
                    {
                      "Ref": "EnvType"
                    },
                    " >> /path/yourfile\n"
                  ]
                ]
              }
            }
          }
      

      这会将EnvType 参数附加到您实例中的文件/path/yourfile 中。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-07-10
        • 1970-01-01
        • 2021-05-25
        • 2020-09-12
        • 2018-11-17
        • 1970-01-01
        相关资源
        最近更新 更多