G
GuideDevOps
Lesson 6 of 9

Multi-line Strings

Part of the YAML tutorial series.

When to use Block Scalars

In DevOps, we often need to store long blocks of text inside a YAML file. Common examples include:

  • Bash or Python scripts inside a Kubernetes ConfigMap.
  • SSH Public Keys or SSL Certificates.
  • Detailed descriptions in an OpenAPI/Swagger file.

YAML provides two primary indicators to handle this: the Literal (|) and the Folded (>) operator.


1. The Literal Block (|)

The pipe symbol (|) tells YAML to preserve every newline exactly as it appears in the block.

script: |
  #!/bin/bash
  echo "Beginning Backup"
  tar -czf backup.tar.gz /data
  echo "Backup Complete"

Result: The string will contain the \n characters between each line. This is the standard choice for scripts.


2. The Folded Block (>)

The greater-than symbol (>) tells YAML to fold newlines into spaces.

description: >
  This is a long sentence
  that we broke into several
  lines in the YAML file 
  just to make it easier to read.

Result: The string becomes "This is a long sentence that we broke into several lines in the YAML file just to make it easier to read."

This is used for long human-readable descriptions where you don't want the line breaks to appear in the final output.


3. Chomping (The + and - modifiers)

"Chomping" controls what happens to the blank lines at the end of your block. This is a very subtle but important feature when dealing with certificates or code that is sensitive to trailing newlines.

Clip (Default)

Removes the final newline of the block.

Strip (|- or >-)

Removes all trailing newlines.

key: |-
  ---BEGIN KEY---
  A1B2C3D4...
  ---END KEY---

Keep (|+ or >+)

Preserves any and all trailing newlines exactly as they appear.


Pro Tip: Indentation is Fixed

When using a block scalar, the indentation level of the first line determines the indentation level for the rest of the block. If you accidentally misalign one line, your script might fail to run or be parsed correctly!