CloudFormation: Multiline Strings

Hello!

If you’re asking how to do multiline strings in CloudFormation’s JSON syntax: I recommend switching to YAML.

There are a bunch of ways to do multiline strings in YAML, so there are a bunch of ways to do them in CloudFormation. For inline code, write them as Literal Block Scalars with a vertical pipe (|). Like in this lambda function:

Function:
  Type: AWS::Lambda::Function
  Properties:
    Code:
      ZipFile: |
        def handler(event, context):
            print('Huzzah!')
    Handler: index.handler
    Role: !GetAtt ExecutionRole.Arn
    Runtime: python3.7

This preserves newlines, so it’ll create a function whose code looks the same as it does in the CloudFormation template:

def handler(event, context):
    print('Huzzah!')

For parameter descriptions, any of the formats work. My stacks are usually managed by a CI/CD pipeline, so users read the descriptions from the actual template code when they’re choosing parameter values to pass to the pipeline. Any non-erroring syntax is fine, it’s just a code style choice. Even if you use the web console you’re still good, they all render the same:

Parameters:
  FlowScalar:
    Type: String
    Description:
      This is a parameter is and I want to write a long description. That will
      be easier to read if I split it onto several lines.
  FoldedBlockScalar:
    Type: String
    Description: >
      This is a parameter is and I want to write a long description. That will
      be easier to read if I split it onto several lines.
  LiteralBlockScalar:
    Type: String
    Description: |
      This is a parameter is and I want to write a long description. That will
      be easier to read if I split it onto several lines.

MultilineParameterDescriptions

I often use Literal Block Scalars with a vertical pipe (|) for these just so I don’t have to remember which pattern to use in which case.

Happy automating!

Adam

Need more than just this article? I’m available to consult.

You might also want to check out these related articles: