我正在尝试根据可选参数创建条件。选项是是否从我的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示例明显在Conditions块中使用!Ref。
EnvType:
Description: Environment type.
Default: test
Type: String
AllowedValues:
- prod
- test
ConstraintDescription: must specify prod or test.
Conditions:
CreateProdResources: !Equals [ !Ref EnvType, prod ]
有人可以提供有关如何实施此条件的原因或为什么为此实施引发此错误消息的反馈吗?
答案 0 :(得分:2)
根据docs,条件应在要有条件创建的资源的顶层使用。
不支持在实例Condition
部分中插入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
答案 1 :(得分:1)
您也可以在userData中使用条件。我关注了这篇帖子https://www.singlestoneconsulting.com/blog/cloudformation-mapping-and-conditionals-making-your-templates-more-universal/,它确实有效