简体   繁体   English

如何将变量传递到 AWS Cloudformation cfn-init 文件内容

[英]How to pass variable into AWS Cloudformation cfn-init files content

I want to change my Instances UserData to MetaData:->AWS::CloudFormation::Init:->files:->content.我想将我的 Instances UserData 更改为 MetaData:->AWS::CloudFormation::Init:->files:->content。

My difficulty is with my existing UserData Bash script because it has variables and I want to have the variables in the cfn-init files content section.我的困难在于我现有的 UserData Bash 脚本,因为它有变量,我想在 cfn-init 文件内容部分中有变量。

Here is the existing UserData and it is the last 6 lines I want to transfer to the cfn-init.这是现有的 UserData,它是我要传输到 cfn-init 的最后 6 行。 How are variables used in the content section?内容部分如何使用变量?

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

This can be a bit finicky to get right, but you can use a Fn::Sub to interpolate parameters into the user data:这可能有点挑剔,但您可以使用Fn::Sub将参数插入到用户数据中:

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

The reason it's finicky is that CFN and Bash can both use the ${…} style for variable substitution, so make sure to use that syntax only for CFN parameters.之所以如此挑剔,是因为 CFN 和 Bash 都可以使用${…}样式进行变量替换,因此请确保仅对 CFN 参数使用该语法。

Note that you can use the !Base64 and !Sub shorthand for one of the functions, but not both, CFN doesn't support nested shorthand function calls.请注意,您可以将!Base64!Sub简写用于其中一个函数,但不能同时使用两者,CFN 不支持嵌套简写 function 调用。

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

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