Understanding multi line strings in YAML and Ansible (Part I - YAML)
I had a strange problem with variables spanning multiple lines in Ansible. During the process of debugging it, I learned a bit about multi line strings which are called “blocks” in the official YAML specification. In this blog post we’ll examine the different YAML block styles and block chomping methods. In Part II we will then learn the use cases and quirks of each style when used in Ansible.
We’ll run this base playbook for each style via ansible-playbook -v playbook.yml
and will only replace the variable with the corresponding style.
---
- hosts: localhost
connection: local
vars:
my_pattern: |
With his own sword,
Which he did wave against my throat, I have ta’en
His head from him.
tasks:
- debug:
var: my_pattern
Styles
There are two basic styles of blocks in YAML, literal and folded. Both have different advantages and disadvantages, especially when used in Ansible.
Literal
According to the YAML specification literal is “is the simplest, most
restricted, and most readable scalar style”. It’s denoted by the pipe, |
:
my_pattern: |
With his own sword,
Which he did wave against my throat, I have ta’en
His head from him.
Output:
ok: [localhost] => {
"my_pattern": "With his own sword,\nWhich he did wave against my throat, I have ta’en\nHis head from him.\n"
}