How to define and test for a null string in AWS CloudFormation template?

Viewed 5082

I have a CloudFormation template that accepts this parameter

TargetGroupName:
  Type: String
  Description: 'Parameter to override target group name'
  Default: ''

However, instead of an empty string as default, how can I define is as a Null string, like this? I know Null is NOT a valid keyword, but I wanted to illustrate what I wanted to do.

TargetGroupName:
  Type: String
  Description: 'Parameter to override target group name'
  Default: Null

And then, how can I set a condition to test for the Null string, like this?

Conditions:
  CreateTargetGroup:
    !Not [ !Equals [ !Ref TargetGroupName, Null ] ]

Of course the keyword Null throws a CloudFormation script validation exception since it's NOT a valid keyword.

1 Answers

You can do it like this:

Parameters:

TargetGroupName:
    Description: 'Parameter to override target group name'
    Type: String
    Default: ""

Condition:

  IsTargetGroupNameEmpty:  !Equals [!Ref "TargetGroupName", ""]

And then in every resource that you don't want to create just pass this line:

!If [ IsTargetGroupNameEmpty, [ !Ref <RESOURCE_NAME> ], !Ref "AWS::NoValue" ]

Please take a look on this docs: https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/pseudo-parameter-reference.html#cfn-pseudo-param-novalue

Related