Search code examples
amazon-web-servicesaws-cloudformation

Use a default value less than MinLength in an AWS CloudFormation parameter


I'm building an AWS CloudFormation template which has the following parameter:

Naming:
  Type: String
  Default: aws-ab-
  MinLength: 12
  Description: 'aws-ab-{customer}-{environment}'

The first characters are fixed, but the rest needs to be configured.

However, this template is giving me an error:

Template contains errors.: Parameter 'Naming' must contain at least 12 characters

Is there a way to have a default/placeholder value that knowingly violates the validation rules, expecting that the user will complete it?


Solution

  • In this case, you've defined the Naming parameter with a MinLength constraint of 12 characters, and it's causing an error because the default value you provided, 'aws-ab-', is shorter than the minimum length constraint.

    To achieve your goal of having a default/placeholder value that knowingly violates the validation rules and expecting users to complete it, you can work around this constraint by using a combination of intrinsic functions like Fn::Sub to construct the default value. Here's how you can do it:

    Parameters:
      Customer:
        Type: String
        Default: customer
        AllowedPattern: ^[a-z0-9]+$  # Only lowercase letters and digits are allowed
      Environment:
        Type: String
        Default: environment
        AllowedPattern: ^[a-z0-9]+$  # Only lowercase letters and digits are allowed
    
    Resources:
      MyResource:
        Type: AWS::SomeResourceType
        Properties:
          Naming:
            Fn::Sub: 'aws-ab-${Customer}-${Environment}'
    

    In this example:

    • We have two additional parameters, Customer and Environment, which have default values.
    • The Fn::Sub function is used to substitute the default value of Naming with the concatenated string 'aws-ab-${Customer}-${Environment}'.

    This way, the default value for Naming is constructed using the Fn::Sub function, and it doesn't violate the MinLength constraint because the placeholders ${Customer} and ${Environment} will be replaced by their default values when the CloudFormation stack is created. Users can later override these values when creating the stack if needed.