Ansible - different forms of yaml syntax

Mar 31, 2015   #ansible  #yaml 

I had reason to review some of the various styles of yaml that can be used in an ansible playbook recently. The following is a rough guide.

Note: indentation in yaml is crucial!

# e.g. in vim :set tabstop=2 shiftwith=2 expandtab :retab

Note: It’s recommended to always use the yaml dict format

--- - hosts: foo vars: fname: /tmp/foo tasks: - name: single line plain style file: path={{ fname }} state=touch - name: multi line plain style file: path={{ fname }} state=absent #- name: alternative multi line plain style # file: # path={{ fname }} # state=absent - name: multi line double quoted style file: "path={{ fname }} state=touch" - name: multi line single quoted style file: 'path={{ fname }} state=absent' # With the yaml 'folded' style, anything in a new line (and indented) below a > # is essentially a single string that has been wrapped. new line chars are not # preserved unless the line is further indented or is an empty line. - name: multi line with folded style file: > path={{ fname }} state=touch # Note we have to quote the {{ }} in this situation as otherwise yaml will # see it as a hash/dict - name: yaml dict format - preferred file: path: "{{ fname }}" state: absent - name: yaml dict format - using folded style copy: dest: "{{ fname }}" content: > this is a string that will be one line in the file - shell: cat {{ fname }} register: result - debug: var=result - name: yaml dict format - using literal style, good for cert files copy: dest: "{{ fname }}" content: | this is a string that will have new lines preserved - shell: cat {{ fname }} register: result - debug: var=result

One of the reaons for using the yaml dict notation is that type setting is preserved, e.g.

myjsonvar: {"foo": "bar"} # this will not work, as the value will be treated as a string - set_fact: myvar={{myjsonvar}} # whereas this will correctly create a dict var - set_fact: myvar: "{{ myjsonvar }}"