使用 Amazon Cloudformation 构建配置文件

Building configuration files with Amazon Cloudformation

我正在构建一个 Amazon CloudFormation 脚本,它需要我配置一个反向代理并填充一些值。我见过有人这样做:

"Fn::Join": [
  "",
  [
    "events {\n",
    "  worker_connections 1024;\n",
    "}\n",
    "http {\n",
    "  server {\n",
    "    location / {\n",
    "      proxy_pass http://",
    {
      "Fn::GetAtt": [
        "FELoadBalancer",
        "DNSName"
      ]
    },
    ";\n",
    "      proxy_read_timeout 90;\n",
    "      proxy_redirect default;\n",
    "      proxy_set_header Host $host:$server_port;\n",
    "      proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;\n",
    "      proxy_set_header X-Real-IP $remote_addr;\n",
    "    }\n",
    "  }\n",
    "}\n"
  ]
]

但这太丑了。

是否有更易读且更易于维护的方式来构建这些配置部分?

CloudFormation 支持的唯一格式是 JSON 和 YAML。

有关 YAML 的详细信息,请参阅 the CloudFormation docs

您还可以使用允许您以不同格式对基础架构进行编码的第三方框架,并让他们为您提炼成 JSON/YAML。请参阅 this example 了解流行的框架。

您可能想看看小胡子模板。我没有用过它们,但看起来这就是它们的用途。

http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-init.html#aws-resource-init-files

已经建议,改用 YAML,https://aws.amazon.com/blogs/aws/aws-cloudformation-update-yaml-cross-stack-references-simplified-substitution/,类似于:

UserData:
  'Fn::Base64': !Sub
    - |
      events {
        worker_connections 1024;
      }
      http {
        server {
          location / {
            proxy_pass http://"
              Fn::GetAtt:
                FELoadBalancer
                DNSName
              ;
            proxy_read_timeout 90;
            proxy_redirect default;
            proxy_set_header Host $host:$server_port;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_set_header X-Real-IP $remote_addr;
          }
        }
      }

除此之外,您还可以使用可以在实例上的文件中定义的云 boothook? http://cloudinit.readthedocs.io/en/latest/topics/format.html#cloud-boothook