Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 236
Nasir Ahmad Avatar asked Jun 28 '18 16:06

Nasir Ahmad


People also ask

Does CloudFormation have nested stack?

Nested stacks are stacks created as part of other stacks. You create a nested stack within another stack by using the AWS::CloudFormation::Stack resource. As your infrastructure grows, common patterns can emerge in which you declare the same components in multiple templates.

Which two types of syntax can be used within an AWS CloudFormation template?

You can author AWS CloudFormation templates in JSON or YAML formats. We support all AWS CloudFormation features and functions for both formats, including in AWS CloudFormation Designer.

Which section of CloudFormation template does not allow for conditions?

According to the docs, Conditions should be used at the top level of the resource you want to conditionally create. Putting a Condition inside the Instance UserData section isn't supported. To use Conditions in your situation, you'd want separate Resources conditionally created based on the Parameter.


1 Answers

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.

like image 110
Nasir Ahmad Avatar answered Sep 22 '22 22:09

Nasir Ahmad