Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If else condition cloudformation

I would like to populate a value in cloudformation depending on input parameter. I want to assign Name as either test-svc.abc.com or svc.abc.com depending on whether environment name is prod or not. If the environnment name is prod then the value should be svc.abc.com otherwise it should always be {env-name}-svc.abc.com.

I have the following expression:

Name: !Join [ '-', [ !Ref EnvironmentName, !Ref 'HostedZoneName' ] ]

In the above expression, HostedZoneName will be passed as svc.abc.com and the value of EnvironmentName could be test, release or prod. So the conditions should be evaluated as:

Inputs: HostedZoneName -> svc.abc.com, EnvironmentName -> test
Output: test-svc.abc.com

Inputs: HostedZoneName -> svc.abc.com, EnvironmentName -> release
Output: release-svc.abc.com

Inputs: HostedZoneName -> svc.abc.com, EnvironmentName -> 1234567
Output: 1234567-svc.abc.com

Inputs: HostedZoneName -> svc.abc.com, EnvironmentName -> prod
Output: svc.abc.com

It's basically ternary operator.

Name = EnvironmentName.equals("prod") ? HostedZoneName : EnvironmentName + "-" + HostedZoneName

Struggling with if else condition in CloudFormation.

like image 245
kk. Avatar asked Jan 27 '23 07:01

kk.


2 Answers

Take a look at Cloudformation Conditions. You can use them to define if-statements using Fn::If

Then you can use this condition in the Resources section to define how to build your HostedZoneName.

Here's an example. You'll probably need to do something like this:

...
 "Conditions" : {
    "CreateProdResources" : {"Fn::Equals" : [{"Ref" : "EnvType"}, "prod"]}
  },

...

"Properties" : {
    "HostedZoneName" : {
      "Fn::If" : [
        "CreateProdResources",
        "svn.abc.com",
        {"Fn::Sub": "${Environment}-svc.abc.com"}
      ]}
  },
like image 112
rdas Avatar answered Jan 29 '23 07:01

rdas


Based on the answer posted by @rdas, I've implemented below expression in YAML format:

...
Conditions: 
  IsProductionEnvironment: !Equals [ !Ref EnvironmentName, prod ]
...

...
Name: !If [IsProductionEnvironment, !Ref 'HostedZoneName', !Join [ '-', [ !Ref EnvironmentName, !Ref 'HostedZoneName' ] ]]
...
like image 36
kk. Avatar answered Jan 29 '23 08:01

kk.