依赖AWS的云形成条件

时间:2016-12-12 12:14:06

标签: amazon-web-services cloud amazon-cloudformation

我正在编写一个云形成模板,并且我的堆栈中的资源创建取决于环境。
因此,我检查一个参数(Environment)的值,并根据它创建该资源(条件:ISProduction)。
但是,我的问题是,在创建资源(MyProductionResource)的情况下,另一个资源(AnotherResource)变得依赖于它并且需要使用另一个(MyProductionResource)的输出属性。 代码如下:

Conditions:
  ISProduction:
    "Fn::Equals":
      - !Ref Environment
      - production
 ...

 MyProductionResource:
    Type: AWS::CloudFormation::Stack
    Condition: ISProduction
    Properties:
    [.. properties..]

 AnotherResource:
    Type: AWS::CloudFormation::Stack
    DependsOn:
      - AResource
      - MyProductionResource
    Properties:
      TemplateURL: whatever
      Parameters:
        AParameter: !GetAtt MyProductionResource.Outputs.SomeString

我的问题是,只有当ISProduction为true时,我才希望AnotherResource依赖于MyProductionResource。一个想法是在DependsOn项中添加某种条件,或任何会带来相同结果的条件。
我如何在AWS Cloud Formation上做到这一点? 此外,我不确定在未创建dependsOn列表中列出的资源时会发生什么。云形成模板会产生错误吗?如何使这个属性读取安全!GetAtt MyProductionResource.Outputs.SomeString?

2 个答案:

答案 0 :(得分:2)

你可以使用!如果是参数

AParameter: !If [ISProduction, !GetAtt MyProductionResource.Outputs.SomeString, "default value?!?"]

但遗憾的是DependsOn不允许使用Fn :: If。

所以你可以创建两次资源。

AnotherProductionResource:
  Type: AWS::CloudFormation::Stack
  Condition: ISProduction
  DependsOn:
  - AResource
  - MyProductionResource
  Properties:
    [...]
AnotherNonProductionResource:
  Type: AWS::CloudFormation::Stack
  Condition: ISNotProduction
  DependsOn:
  - AResource
  Properties:
    [...]

但是如果有这么多ifs,那么你的环境应尽可能地相似。那么也许你可以摆脱这一切?

答案 1 :(得分:0)

这里是“ DependsOn不允许Fn :: If”的替代方法。

Conditions:
  CreateConfigRecorder: !Equals [ !Ref ConfigRecorderExists, 'false' ]

Resource:
#my 1st AWS Resource
  ConfigRecorder: 
    Condition: CreateConfigRecorder
    Type: AWS::Config::ConfigurationRecorder
    *more codes below*

#added, since DependsOn: !If is not possible, trigger by WaitCondition if CreateConfigRecorder is true
#Hacks: https://garbe.io/blog/2017/07/17/cloudformation-hacks/
  ConfigRecorderWaitHandle: 
    Condition: CreateConfigRecorder
    DependsOn: ConfigRecorder
    Type: "AWS::CloudFormation::WaitConditionHandle"
#added, since DependsOn: !If is not possible, trigger by WaitCondition if CreateConfigRecorder is false
  WaitHandle: 
    Type: "AWS::CloudFormation::WaitConditionHandle"
#added, since DependsOn: !If is not possible
  WaitCondition: 
    Type: "AWS::CloudFormation::WaitCondition"
    Properties: 
      Handle: !If [CreateConfigRecorder, !Ref ConfigRecorderWaitHandle, !Ref WaitHandle]
      Timeout: "1"
      Count: 0
#my 2nd AWS Resource that requires DependsOn Attribute
  AWSConfigRule:
    Type: AWS::Config::ConfigRule
    DependsOn: WaitCondition #added, since DependsOn: !If is not possible
    *more codes below*

基本上,如果我的第一资源不存在,则在运行CFN之前,我的第二资源仅具有DependsOn属性。我是从https://garbe.io/blog/2017/07/17/cloudformation-hacks/

获得的