AWS CloudFormation:结合 ImportValue 和 Sub 函数会导致错误

fiz*_*zer 7 yaml amazon-web-services aws-cloudformation

将我的模板上传到 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}
Run Code Online (Sandbox Code Playgroud)

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

tia*_*anz 7

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

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

您可以将最后几行更改为:

command: !Sub
    - "touch ${filename}"
    - filename: !ImportValue myexport
Run Code Online (Sandbox Code Playgroud)


pra*_*sun 7

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

UserData:
  Fn::Base64:
    !Sub
    - |
      #!/bin/bash -xe
      echo ${VpcId}
    - VpcId: !ImportValue MyVPCId
       
Run Code Online (Sandbox Code Playgroud)


joa*_*kim 5

就像接受答案的语法替代方案一样,人们可能更喜欢这样做:

command: !Sub ['touch ${filename}', filename: !ImportValue myexport]
Run Code Online (Sandbox Code Playgroud)