Home > front end >  How to use a list in a when conditional in Ansible playbook
How to use a list in a when conditional in Ansible playbook

Time:07-06

I'm trying to check if certain mount points have been added but only want to see those I added which are stored into added_mounts.

How to feed a list which is in a variable to a when conditional as in underneath example?

Sorry if my wording is not up to scratch but I'm still learning.

I'm using Ansible 2.9.

I've tried to use vars_files and make a list and place it in ./host_vars/test/added_mounts or in ./vars/added_mounts but it does not help.

I was thinking to try with a loop in the when conditional but underneath does not work.

when: item.device == {{ item }}
loop: added_mounts

One item in the list works:

- name: "check mounted directories"
  hosts: test
  vars:
    - added_mounts: '/dev/sda1'
  
  tasks:

    - name: Show only Mount point and device info
      debug:
        msg: "{{ item.mount }} - {{ item.device }}"
      loop: "{{ ansible_facts.mounts }}"
      loop_control:
        label: "{{ item.mount }} - {{ item.device }}"
      when: item.device == added_mounts

Several items in the list doesn't work:

- name: "check mounted directories"
  hosts: test
  vars:
    - added_mounts:
        - '/dev/sda1'
        - '/dev/mapper/vg_abc-lv_abc'
  tasks:

    - name: Show only Mount point and device info
      debug:
        msg: "{{ item.mount }} - {{ item.device }}"
      loop: "{{ ansible_facts.mounts }}"
      loop_control:
        label: "{{ item.mount }} - {{ item.device }}"
      when: item.device == added_mounts

If anyone has any hints or pointing to the obvious, I would be most grateful.

CodePudding user response:

You already have a hint in the comments to make a condition on your loop which answers your direct question.

Meanwhile you don't even need a condition in that case. You can select the existing mounts using your list directly from source using the selectattr filter. For a reference see Data manipulation in ansible (where you will actually find an example which almost perfectly matches your question).

Here is an example:

- name: Show only Mount point and device info
  debug:
    msg: "{{ item.mount }} - {{ item.device }}"
  loop: "{{ ansible_facts.mounts | selectattr('mount', 'in', added_mounts) }}"
  loop_control:
    label: "{{ item.mount }} - {{ item.device }}"
  • Related