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

AWS CloudFormation: Combining ImportValue and Sub functions causes error

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

Template validation error: Template error: the attribute in Fn::ImportValue must not depend on any resources, imported values, or 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 命令。所以在上面的例子中,我想创建一个根据导出值命名的文件。我不明白我正在尝试做的事情的上下文中的错误消息。我已验证导出存在于我创建的另一个堆栈中。

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

里面

还有,如果export值字面上叫myexport,你就不要放在${}里面;仅当它是您在模板中定义的参数时才执行此操作。

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

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

作为已接受答案的语法替代方案,人们可​​能更愿意这样做:

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

你可以

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

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

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