2018年10月10日星期三

Ansible, Jinja2 and Quoting

TL;DR

Ansible allows variable substitution in plays through Jinja2 templating. If a variable starts a string, the string needs to be quoted, either by single quotes or double quotes, so as not to be treated as a mapping by YAML, e.g.

- hosts: app_servers
  vars:
    app_path: "{{ base_path }}/22"

or

- hosts: app_servers
  vars:
    app_path: '{{ base_path }}/22'


The Story

I had been aware of the whole variable substitution thing, but under the impression that quoting can only be done with double quotes, probably because of the official example. I was reading some code by a colleague of mine and realized single quote also works under such circumstances. I then digged a little further and here is what I've got.


The Rationale

  1. Single quotes or double quotes are for the YAML interpreter. The difference is that certain escaping sequences could be applied in double quotes for special meanings, like "\n" for a new line, but in single quotes they will be kept as is.
  2. Jinja2 variable substitution, denoted by {{}}, is not escaping. It is for the Jinja2 interpreter, one level higher in Ansible's processing stack.
  3. Quoting a Jinja2 variable started string is merely so that it is not treated as a mapping by the YAML interpreter. So if a string contains variables but doesn't start with any, it doesn't even need quoting.

没有评论:

发表评论