AWS cloudformation。组合ImportValue和Sub函数会导致错误

时间:2018-03-27 08:25:57

标签: amazon-web-services amazon-cloudformation

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

  

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

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

Resources:
      EC2Instance:
        Type: "AWS::EC2::Instance"
        Properties:
          ImageId: ami-3bfab942 #Amazon Linux AMI
          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命令。所以在上面的例子中,我想创建一个基于导出值命名的文件。在我尝试做的事情中,我不理解错误信息。我已经验证了导出存在于我创建的另一个堆栈中。

4 个答案:

答案 0 :(得分:2)

问题不是Sub,但您没有正确使用ImportValue。您在代码中实际导入的内容不是myexport,而是touch ${myexport}整体。您应该将ImportValue放在Sub内。

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

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

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

答案 1 :(得分:1)

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

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

答案 2 :(得分:0)

你可以用

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

答案 3 :(得分:0)

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

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