首页 > 解决方案 > 无法在 UserData AWS EC2 cloudformation 中写入文件的内容

问题描述

我想在不提供如下内联内容的情况下获取 UserData 中文件的内容,但是当 ec2 启动时,我在内容中获取文件的路径,而不是文件的内容。

这是我的模板的片段:

  ServiceInstance:
    Type: "AWS::EC2::Instance"
    Properties:
      . . . 
      UserData:
        'Fn::Base64': !Sub |
          #cloud-config
          write_files:
            - path: /etc/sysconfig/cloudformation
              permissions: 0644
              owner: root
              content: |
                STACK_NAME=${AWS::StackName}
                AWS_REGION=${AWS::Region}
            - path: /etc/path-to-file/conf.yaml
              permissions: 0644
              owner: root
              content: "@file://./config/conf-${Env}.yaml"
          runcmd:
            ## run some commands

当我 ssh 到 ec2 并检查文件内容时,我得到了这个:

[ec2-user@ec2ip ~]$ cat /etc/path-to-file/conf.yaml
@file://./config/conf-dev.yaml

我检查了这个cloud init docs,但找不到相关的东西。知道我在这里做错了什么吗?

标签: amazon-web-servicesamazon-ec2user-datacloud-init

解决方案


将文件内容编码为 base64 并将其作为参数传递。Cloud Init 将对字符串b64进行解码。注意模板和变量的 cloudformation 大小限制。

Parameters:
  ConfContent:
    Type: String
    Description: "Conf content in base64 format."

Resources:
  ServiceInstance:
    Type: "AWS::EC2::Instance"
    Properties:
      . . . 
      UserData:
        'Fn::Base64': !Sub
          - |
            #cloud-config
            write_files:
              - path: /etc/sysconfig/cloudformation
                permissions: 0644
                owner: root
                content: |
                  STACK_NAME=${AWS::StackName}
                  AWS_REGION=${AWS::Region}
              - path: /etc/path-to-file/conf.yaml
                permissions: 0644
                owner: root
                content: ${CONF_CONTENT}
                encoding: b64
            runcmd:
              ## run some commands
          - CONF_CONTENT: !Ref ConfContent

然后将文件内容公开为属性:

aws cloudformation create-stack \
  --stack-name "mystack" \
  --template-body "template.yaml" \
  --parameters \
    ParameterKey=ConfContent,ParameterValue=\"$(base64 -w0 ./config/conf-dev.yaml)\"

推荐阅读