Ansible Group Vars – Using Without With_Items

ansible

I have defined group_vars to mount nfs shares on numerous hosts based on their environment:

---
mounts:
- path: /home/user1
  src: 10.0.0.1:/home/user1
  fstype: nfs
  state: present
- path: /home/user2
  src: 10.0.0.1:/home/user2
  fstype: nfs
  state: present

In my playbook I have the following task to add those mounts:

---
- hosts: clients
  tasks:
  - name: mounts
    mount:
      path: "{{ item.path }}"
      src: "{{ item.src }}"
      fstype: "{{ item.fstype }}"
      opts: "{{ item.opts }}"
      state: "{{ item.state }}"
    with_items: "{{ mounts }}"

Now I was wondering if there is a shorthand to achieve the same thing? E.g.

---
- hosts: clients
  tasks:
  - name: mounts
    mount: "{{ mounts }}"

Best Answer

The module is not capable of making several mounts in a single call, so you will still have to go through each individual mount definition with a loop. But you can set all parameters in one go from your individual dicts.

Before I write the (easy) solution, you should still be warned that setting tasks arguments like this is discouraged in ansible doc because it can be unsafe in some circumstances. This is why you will get a warning when using the code below:

- hosts: clients
  tasks:
    - name: mounts
      mount: "{{ item }}"
      with_items: "{{ mounts }}"