【问题标题】:Using Conditions and Parameters in CloudFormation在 CloudFormation 中使用条件和参数
【发布时间】:2019-01-05 02:06:31
【问题描述】:

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

参数和条件如下所示:

Parameters: 
  EnvType: 
    Description: Option to install New Relic Infrastructure.
    Default: apm
    Type: String
  AllowedValues: 
    - apm
    - +infra

然后是我的带有条件启动脚本的 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

我收到的错误消息是: 模板验证错误:模板格式错误:未解决的依赖项 [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 ]

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

【问题讨论】:

标签: amazon-web-services amazon-cloudformation


【解决方案1】:

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

不支持将 Condition 放入 Instance UserData 部分。

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

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

【讨论】:

    【解决方案2】:

    您也可以在 userData 中使用条件。我关注了这篇帖子https://www.singlestoneconsulting.com/blog/cloudformation-mapping-and-conditionals-making-your-templates-more-universal/,它确实有效

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-03
      • 1970-01-01
      • 1970-01-01
      • 2020-05-01
      • 2019-01-06
      • 2021-12-16
      • 2018-05-03
      • 2021-02-06
      相关资源
      最近更新 更多