83

I'm trying to specify a boolean parameter in a CloudFormation template so I can conditionally create resources based on a parameter passed in.

Looking at the documentation here and here it would appear there is a discernible lack of a boolean data type.

What is best practice for specifying a boolean? possibly Number with 0 or 1 or String with AllowedValues 'true' and 'false'?

wjordan
  • 19,770
  • 3
  • 85
  • 98
Willem van Ketwich
  • 5,666
  • 7
  • 49
  • 57

1 Answers1

123

The Quick Start templates are a good, semi-official reference point of how complex templates can/should be created, and they implement Boolean values for Conditional resources exactly as you described, using a String with AllowedValues true and false. Here's a specific example:

"EnableBanner": {
    "AllowedValues": [
        "true",
        "false"
    ],
    "Default": "false",
    "Description": "To include a banner to be displayed when connecting via SSH to the bastion, set this parameter to true",
    "Type": "String"
}

A similar example can be found in the Conditionally use an existing resource example from the CloudFormation documentation, where the AllowedValues are default or NONE (the default).

To conditionally create a resource based on such a boolean parameter, you add a Condition statement containing a Fn::Equals intrinsic function matching true, then add a Condition key to the resource.

Here's a complete, minimal example template:

Launch Stack

Parameters:
  CreateResource:
    Description: Whether I should create a resource.
    Default: false
    Type: String
    AllowedValues: [true, false]
Conditions:
  ShouldCreateResource:
    !Equals [true, !Ref CreateResource]
Resources:
  Resource:
    Type: AWS::CloudFormation::WaitConditionHandle
    Condition: ShouldCreateResource
wjordan
  • 19,770
  • 3
  • 85
  • 98
  • 8
    I'm still unclear as to whether the string `'true'` and the literal `true` evaluate to the same thing. I see examples of both cases in the documentation, seemingly used interchangeably. – Arel May 29 '19 at 21:14
  • 6
    @Arel, in YAML, `'true'` and `true` are both strings. Quotes around strings are usually optional. Some exceptions are when numbers or special characters are involved. – Mark R Jun 12 '19 at 17:45
  • 16
    @arel @MarkR the YAML-spec [tag resolution](https://yaml.org/spec/1.2/spec.html#id2805071) explicitly resolves `true` to a native-boolean type, so `'true'` and `true` do not evaluate to the same thing, at least in YAML itself. In CloudFormation, for String-type Parameter values at least it seems to convert any YAML-native values to String before validating, so in this case at least `'true'` and `true` may be interchangeable for that reason. – wjordan Jun 12 '19 at 19:28