【问题标题】:AWS CloudFormation: Combining ImportValue and Sub functions causes errorAWS CloudFormation:结合 ImportValue 和 Sub 函数会导致错误
【发布时间】:2018-09-05 13:35:50
【问题描述】:

将我的模板上传到 CloudFormation 时,我收到以下验证错误:

模板验证错误:模板错误:中的属性 Fn::ImportValue 不得依赖于任何资源、导入的值或 Fn::GetAZs

我在下面有一个重现问题的测试模板:

Resources:
  EC2Instance:
    Type: "AWS::EC2::Instance"
    Properties:
      ImageId: ami-3bfab942
      InstanceType: t2.micro
      KeyName: mykeypair
      UserData:
        "Fn::Base64":
          !Sub |
            #!/bin/bash
            yum update -y aws-cfn-bootstrap
            /opt/aws/bin/cfn-init -v --stack ${AWS::StackName} --resource EC2Instance --configsets testset --region ${AWS::Region}
            yum -y update
    Metadata:
      AWS::CloudFormation::Init:
        configSets:
          testset:
            - "testConfiguration"
        testConfiguration:
          commands: 
            CreateTestFile:
              cwd: "~"
              command: 
                "Fn::ImportValue": 
                  !Sub | 
                    touch ${myexport}

为了让事情尽可能简单,我基本上是在尝试使用导出创建一个 bash 命令。所以在上面的例子中,我想创建一个基于导出值命名的文件。在我正在尝试做的事情的背景下,我不明白错误消息。我已验证导出存在于我创建的另一个堆栈中。

【问题讨论】:

  • 你能发布你试图导入价值的资源 sn-p 吗?
  • 您好,我已编辑包含一个具有相同问题的模板。

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


【解决方案1】:

问题不是Sub,而是你没有正确使用ImportValue。您在代码中实际导入的东西不是myexport,而是整体上的touch ${myexport}。你应该把你的ImportValue 放在Sub 里面。

另外,如果导出值的字面意思是myexport,则不要将它放在${} 中;仅当它是您在模板中定义的参数时才执行此操作。

你可以把最后几行改成这样:

command: !Sub
    - "touch ${filename}"
    - filename: !ImportValue myexport

【讨论】:

    【解决方案2】:

    作为公认答案的替代语法,人们可能更愿意这样做:

    command: !Sub ['touch ${filename}', filename: !ImportValue myexport]
    

    【讨论】:

    • 这就是我要找的,谢谢!我想应该先尝试一下。
    【解决方案3】:

    我想做同样的事情,但是使用不同的语法,因为我有多行子函数内容。 下面是对我有用的代码-sn-p。

    UserData:
      Fn::Base64:
        !Sub
        - |
          #!/bin/bash -xe
          echo ${VpcId}
        - VpcId: !ImportValue MyVPCId
           
    

    【讨论】:

      【解决方案4】:

      你可以用

      Command:
         Fn::ImportValue: !Sub "touch-${filename}"
      

      【讨论】:

        猜你喜欢
        • 2021-10-15
        • 2021-07-17
        • 2018-05-09
        • 1970-01-01
        • 2019-03-14
        • 2021-08-10
        • 2020-09-09
        • 2021-07-13
        • 2021-07-27
        相关资源
        最近更新 更多