Delvin Delvin - 1 year ago 227
YAML Question

Ansible syntax best practice, YAML dictionary (key: value) or equal sign (key=value)?

I'm used to see Ansible examples as:

- file: path=/tmp/file state=touch

but someone at work told me that I should be consistent using only YAML syntaxis like this:

- file:
path: /tmp/file
state: touch


- file: {path: /tmp/file, state:touch}

Which one satisfies Ansible best practices?

Mxx Mxx
Answer Source

Taken from

At its core, the Ansible playbook runner is a YAML parser with added logic such as commandline key=value pairs shorthand. While convenient when cranking out a quick playbook or a docs example, that style of formatting reduces readability. We recommend you refrain from using that shorthand (even with YAML folded style) as a best practice.

Here is an example of some tasks using the key=value shorthand:

- name: install telegraf
    name: telegraf-{{ telegraf_version }} state=present update_cache=yes disable_gpg_check=yes enablerepo=telegraf
  notify: restart telegraf

- name: configure telegraf
  template: src=telegraf.conf.j2 dest=/etc/telegraf/telegraf.conf
  notify: restart telegraf

- name: start telegraf
  service: name=telegraf state=started enabled=yes

Now here is the same tasks using native YAML syntax:

- name: install telegraf
  yum: telegraf-{{ telegraf_version }}
    state: present
    update_cache: yes
    disable_gpg_check: yes
    enablerepo: telegraf
  notify: restart telegraf

- name: configure telegraf
    src: telegraf.conf.j2
    dest: /etc/telegraf/telegraf.conf
  notify: restart telegraf

- name: start telegraf
    name: telegraf
    state: started
    enabled: yes

Native YAML has more lines; however, those lines are shorter, reducing horizontal scrolling and line wrapping. It lets the eyes scan straight down the play. The task parameters are stacked and easily distinguished from the next. Native YAML syntax also has the benefit of improved syntax highlighting in virtually any modern text editor out there. Being native YAML, editors such as vim and Atom will highlight YAML keys (module names, directives, parameter names) from their values further aiding the readability of your content. Many of our own docs use this shorthand for legacy reasons though we’re progressively changing that. (Documentation pull requests accepted.)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download