ansible with_items stdout_lines filter

Viewed 4505

I have a list in a variable that I need to execute a shell command against.

   - name: Set Percentage value to "yes" to all disks for NFS SERVERS
    shell: |
      NUM=$(cat -n {{ cdm_path }} |\
            sed -n "/<disk>/,/<\/disk>/p" |\
            sed -n "/<alarm>/,/<\/alarm>/p" |\
            sed -n "/<fixed>/,/<\/fixed>/p" |\
            sed -n "/<{{ item }}>/,/<\/{{ item }}>/p" |\
            awk '/ percent = no/ {printf "%d", $1}')"s";
      if [ "${NUM}" != "s" ]; then
          sed -i "${NUM}/no/yes/g" {{ cdm_path }};
          echo "file_was_changed" ;
      fi
    with_items: "{{ result.stdout_lines }}"
    register: percent_nfs
    when: ansible_hostname == "nfs01" or
          ansible_hostname == "nfs02"
    changed_when: '"file_was_changed" in percent_nfs.stdout'

result contains something like this:

#
#boot
#emc#dest#admin
#emc#dest#dbdata
#emc#dest#dbbackups
#emc#dest#lsgdev
#emc#dest#lsgdev_dev
#emc#dest#lsgdev_stage
#emc#dest#lsglegacy

I am running this code when ansible_hostname == nfs01 or nfs02

I need to keep 'result' the same for multiple devices, but I only want to execute the shell command with items that dont contain *lsg* in the name.

How can I further filter the with_items line to only use the filtered items?

1 Answers

There is likely a more elegant solution to your problem of excluding items, from result.stdout_lines, which don't include the sub-string lsg.

However, one possible solution would be to use a combination of the Ansible difference set theory filter and the Jinja2 select filter (similar to in the following answer) to filter your items, like below:

...
with_items: "{{ result.stdout_lines|difference(result.stdout_lines|select('search','lsg')|list) }}"
...
Related