
Escaping Ansible variables
July 11, 2016
Recently a customer asked me to help him debug an Ansible Playbook that was throwing a very generic error that was not helping at all. The error was:
ERROR! Syntax Error while loading YAML.
As soon as I saw the error, I already guessed which problems could trigger such error: it’s either a bad usage of spaces, a badly escaped column within a value, or a variable escaping problem.
With a couple of grep
runs, I identified it as the variable escaping problem.
Differently from what people believe, in Ansible Playbook, variables can create problems. Even more problematic is the fact that based on the location of the variable, they might or might not create a problem. To be more specific, a variable at the beginning of the value will give problems, while one in the middle of the value does not.
So, effectively:
- debug:
msg: {{ inventory_hostname }} host
will fail, while the following will succeed:
- debug:
msg: host {{ inventory_hostname }}
To make the first one work is enough to escape the value:
- debug:
msg: "{{ inventory_hostname }} host"
Due to Ansible’s fairly inconsistent behavior, my general suggestion is to always escape any value that contains a variable to make it easier and more consistent.