在 AWS Cloud Formation 模板中创建嵌套 If else

Create Nested If else in AWS Cloud Formation Template

我正在我的 CloudFormation 模板中使用 Load Balancer 创建和附加 EC2 实例。 这里是负载均衡器资源中的实例。

"Instances" : [
    "Fn::If": ["AttachLoadBalancerToServer1",
      {
        "Fn::GetAtt": [ "ServerStack1", "Outputs.Server1" ],
      },
      {
        "Fn::If": ["AttachLoadBalancerToServer2",
        {
          "Fn::GetAtt": [ "ServerStack2", "Outputs.Server1" ],
        },""  
      ]
      },""
    ]
],

我想在这个中使用这个 if else 模式:

if(AttachLoadBalancerToServer1){
"Instances" =  "Fn::GetAtt": [ "ServerStack1", "Outputs.Server1" ],
} 
else if(AttachLoadBalancerToServer2){
"Instances" =  "Fn::GetAtt": [ "ServerStack2", "Outputs.Server1" ],
}
else{
"Instances" =  "",
}

任何人都可以帮助我在这个模板中编写 IF ELSEIF 结构吗?我可以添加一个条件,但无法找到如何在一个条件内使用第二个条件。

谢谢

我通过在 AWS CloudFormaiton 模板中添加以下结构来实现嵌套 IF:

    "Instances" : [
        "Fn::If": ["AttachLoadBalancerToServer1",
          {
            "Fn::GetAtt": [ "ServerStack1", "Outputs.Server1" ],
          },
          {
            "Fn::If": ["AttachLoadBalancerToServer2",
            {
              "Fn::GetAtt": [ "ServerStack2", "Outputs.Server1" ],
            },{ "Ref" : "AWS::NoValue"}
          ]
          }
        ]
    ],

这对我来说效果很好。我发布答案是因为如果有人将来遇到同样的问题,我的答案可能会对他有所帮助。

这是一个 yaml 示例

 PlacementStrategies:
    !If 
    - IsPlacementStrategyConfigured
    - 
      !If 
      - IsPlacementStrategiesConfigured
      - 
        - Type: !Ref PlacementStrategyType
          Field: !Ref PlacementStrategyField
        - Type: !Ref PlacementStrategyType2
          Field: !Ref PlacementStrategyField2
      -
        - Type: !Ref PlacementStrategyType
          Field: !Ref PlacementStrategyField
    - !Ref AWS::NoValue