Nasir Ahmad
Nasir Ahmad

Reputation: 463

Create Nested If else in AWS Cloud Formation Template

I am creating and attaching EC2 instance with Load Balancer in my CloudFormation template. here instances in Load Balancer resource.

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

I want to use this if else pattern in this:

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

Any body can help me writing IF ELSEIF structure in this template? I am able to add one condition but not able to find how to use the second condition within one condition.

Thank you

Upvotes: 8

Views: 17824

Answers (2)

sysofadown3
sysofadown3

Reputation: 81

Here's a yaml example

 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

Upvotes: 8

Nasir Ahmad
Nasir Ahmad

Reputation: 463

I achieved the nested IF by adding the following structure in AWS CloudFormaiton template:

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

This worked well for me. I am posting answer because if someone stuck in future about the same problem my answer might help him.

Upvotes: 17

Related Questions