【问题标题】:Ref not getting resolved in user data in cloud formation参考未在云形成中的用户数据中得到解决
【发布时间】:2019-06-04 15:33:29
【问题描述】:

我正在云形成中创建一个 EFS 卷,并尝试在启动模板的用户数据中引用它。

我尝试了多种在 CF 中使用 Ref 的语法,但每次都遇到相同的错误。 我实际上想用 EFS 做不同的事情,但发布的示例代码也不起作用

  ClusterFileSystem:
    Type: AWS::EFS::FileSystem
    Properties:
      Encrypted: true

ClusterLaunchTemplate:
  Type: AWS::EC2::LaunchTemplate
  DependsOn: ClusterFileSystem
  Properties:
    LaunchTemplateName: !Sub ${AWS::StackName}
    LaunchTemplateData:
      ImageId: !Ref 'AMIId'
      SecurityGroupIds: [!GetAtt 'ClusterSecurityGroup.GroupId']
      InstanceType: !Ref 'InstanceType'
      BlockDeviceMappings:
      - DeviceName: "/dev/xvda"
        Ebs:
          VolumeSize: "40"
          VolumeType: "gp2"
          Encrypted: true
      - DeviceName: "/dev/xvdcz"
        Ebs:
          VolumeSize: "22"
          VolumeType: "gp2"
          Encrypted: true
      IamInstanceProfile:
        Name: 'ECSHostInstanceProfile'
      Monitoring:
        Enabled: true
      KeyName: !Ref 'Key'
      UserData:
        Fn::Base64: !Sub |
          #!/bin/bash -xe

          function setup-efs () {

            {
              mkdir -p /ecs-resources/${AWS::StackName}/environment
              EFS_FILE_SYSTEM_ID= !Ref ClusterFileSystem
              echo ${EFS_FILE_SYSTEM_ID} >> /tmp/xyz.txt
            }

这是我得到的错误 -

模板格式错误:模板的资源块中未解决的资源依赖项[EFS_FILE_SYSTEM_ID]调用UpdateStack操作时发生错误(ValidationError):模板格式错误:模板的资源块中未解决的资源依赖项[EFS_FILE_SYSTEM_ID] - "

【问题讨论】:

    标签: amazon-web-services amazon-cloudformation amazon-efs


    【解决方案1】:

    您不需要在!Sub 中使用!Ref,要获得相同的行为,您只需引用${} 中的逻辑ID。

    此外,您需要转义 ${EFS_FILE_SYSTEM_ID},因为您想按字面意思打印它,而不是让 !Sub 解析它。

    UserData:
      Fn::Base64: !Sub |
        #!/bin/bash -xe
    
        function setup-efs () {
    
          {
            mkdir -p /ecs-resources/${AWS::StackName}/environment
            EFS_FILE_SYSTEM_ID= ${ClusterFileSystem}
            echo ${!EFS_FILE_SYSTEM_ID} >> /tmp/xyz.txt
          }
    

    注意${ClusterFileSystem} 的引用和EFS_FILE_SYSTEM_ID 的花括号内的!

    如果您指定模板参数名称或资源逻辑 ID,例如 ${InstanceTypeParameter},AWS CloudFormation 将返回与您使用 Ref 内部函数相同的值。如果您指定资源属性,例如 ${MyInstance.PublicIp},AWS CloudFormation 将返回与您使用 Fn::GetAtt 内部函数相同的值。

    要按字面意思书写美元符号和大括号 (${}),请在左大括号后添加感叹号 (!),例如 ${!Literal}。 AWS CloudFormation 将此文本解析为 ${Literal}。

    https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/intrinsic-function-reference-sub.html

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-11-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-23
      相关资源
      最近更新 更多