在 CloudFormation 中使用条件和参数

Bra*_*lis 4 amazon-web-services aws-cloudformation

我正在尝试根据可选参数创建条件。选项是是否从我的 userData 脚本运行一些额外的安装以进行 EC2 部署。

参数和条件如下所示:

Parameters: 
  EnvType: 
    Description: Option to install New Relic Infrastructure.
    Default: apm
    Type: String
  AllowedValues: 
    - apm
    - +infra
Run Code Online (Sandbox Code Playgroud)

然后我的 EC2 资源与条件启动脚本

Resources:
  Ec2Instance:
    Type: AWS::EC2::Instance
    Properties:
     InstanceType: t2.micro
     ImageId: ami-9c9443e3  #Amazon Linux AMI in Tokyo
     KeyName: tokyocloudformation
     IamInstanceProfile: 'S3EC2'
     SecurityGroupIds:
         - !Ref myNewSecurityGroup   
     UserData:
        Condition: apmOnly
        Fn::Base64:
          |
            #!/bin/bash
            installstuff
      Condition: addInfrastructureAgent
        Fn::Base64:
          |
           #!/bin/bash
           installstuff
           installsomeotherstuff
Run Code Online (Sandbox Code Playgroud)

我收到的错误消息是:模板验证错误:模板格式错误:未解析的依赖项 [EnvTyp]。无法引用模板的条件块中的资源

我明白错误的意思,我相信,但它似乎与 AWS 给出的例子不符。

https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/conditions-section-structure.html。此 AWS 示例清楚地在条件块中使用了 !Ref。

  EnvType: 
    Description: Environment type.
    Default: test
    Type: String
    AllowedValues: 
      - prod
      - test
    ConstraintDescription: must specify prod or test.
  Conditions: 
    CreateProdResources: !Equals [ !Ref EnvType, prod ]
Run Code Online (Sandbox Code Playgroud)

有人可以提供一些关于如何实现此条件或为什么会为此实现抛出此错误消息的反馈吗?

tkw*_*rgs 5

根据docs,应在要有条件地创建的资源的顶层使用条件。

不支持将 aCondition放入 InstanceUserData部分。

要在您的情况下使用条件,您需要根据参数有条件地创建单独的资源。

Resources:
  Ec2InstanceAPMOnly:
    Type: AWS::EC2::Instance
    Condition: apmOnly
    Properties:
     InstanceType: t2.micro
     ImageId: ami-9c9443e3  #Amazon Linux AMI in Tokyo
     KeyName: tokyocloudformation
     IamInstanceProfile: 'S3EC2'
     SecurityGroupIds:
         - !Ref myNewSecurityGroup   
     UserData:
        Fn::Base64:
          !Sub |
            #!/bin/bash
            installstuff

  Ec2InstanceWithInfrastructureAgent:
    Type: AWS::EC2::Instance
    Condition: addInfrastructureAgent
    Properties:
     InstanceType: t2.micro
     ImageId: ami-9c9443e3  #Amazon Linux AMI in Tokyo
     KeyName: tokyocloudformation
     IamInstanceProfile: 'S3EC2'
     SecurityGroupIds:
         - !Ref myNewSecurityGroup   
     UserData:
        Fn::Base64:
          !Sub |
            #!/bin/bash
            installstuff
            installsomeotherstuff
Run Code Online (Sandbox Code Playgroud)