【问题标题】:How to pass variable into AWS Cloudformation cfn-init files content如何将变量传递到 AWS Cloudformation cfn-init 文件内容
【发布时间】:2020-08-17 16:05:28
【问题描述】:

我想将我的 Instances UserData 更改为 MetaData:->AWS::CloudFormation::Init:->files:->content。

我的困难在于我现有的 UserData Bash 脚本,因为它有变量,我想在 cfn-init 文件 content 部分中包含变量。

这是现有的 UserData,它是我要传输到 cfn-init 的最后 6 行。 content 部分如何使用变量?

UserData: 
    Fn::Base64: |
      #!/bin/bash -xe
      yum update -y
      yum install -y httpd
      systemctl start httpd
      systemctl enable httpd
      ID=`curl -s http://169.254.169.254/latest/meta-data/instance-id`
      AVAIL_ZONE=`curl -s http://169.254.169.254/latest/meta-data/placement/availability-zone`
      REGION=`curl http://169.254.169.254/latest/dynamic/instance-identity/document|grep region|awk -F\" '{print $4}'`
      echo "This is Server * $ID * in AWS Region $REGION in AZ $AVAIL_ZONE<br>" > /var/www/html/index.html
      EC2_AVAIL_ZONE=$(curl -s http://169.254.169.254/latest/meta-data/placement/availability-zone)
      echo "<h1>Hello World from $(hostname -f) in AZ $EC2_AVAIL_ZONE </h1><br>" >> /var/www/html/index.html

【问题讨论】:

    标签: amazon-web-services amazon-cloudformation


    【解决方案1】:

    这可能有点挑剔,但您可以使用Fn::Sub 将参数插入到用户数据中:

    UserData:
      Fn::Base64:
        Fn::Sub: |
          #!/bin/bash -xe
          echo "${ThisIsACloudFormationParameter}"
    

    之所以如此挑剔,是因为 CFN 和 Bash 都可以使用 ${…} 样式进行变量替换,因此请确保仅对 CFN 参数使用该语法。

    请注意,您可以将 !Base64!Sub 简写用于其中一个函数,但不能同时使用两者,CFN 不支持嵌套的简写函数调用。

    【讨论】:

    • Metadata: AWS::CloudFormation::Init: config: files: "/var/www/html/index.html": content: Fn::Sub: | ${ThisIsACloudFormationParameter}
    • 是的,除非有一些特殊情况Fn::SubAWS::CloudFormation::Init 中不起作用,但我不这么认为。
    猜你喜欢
    • 1970-01-01
    • 2019-06-13
    • 1970-01-01
    • 1970-01-01
    • 2016-02-14
    • 1970-01-01
    • 2017-04-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多