0

I'm preparing a playbook to find the newly scanned HDD from vmware, I used below filtering to fetch the no. of HDDs:

before_add: "{{ hostvars[inventory_hostname].ansible_devices.keys() | select('string') | list }}"

OUTPUT- ['sr0', 'sda', 'sdb', 'sdc', 'dm-2', 'dm-3', 'dm-0', 'dm-1']

then add a new HDD using vmware_guest_disk module and then I executed the setup module to fetch the latest no. of disks

after_add: "{{ hostvars[inventory_hostname].ansible_devices.keys() | select('string') | list }}"

OUTPUT: ['sr0', 'sda', 'sdb', 'sdc', 'sdd', 'dm-2', 'dm-3', 'dm-0', 'dm-1']

Since the managed host is remote node, I'm not able to think of lookup and difference filtering. Kindly suggest how to fetch the difference: "SDD"

Vladimir Botka
  • 3,791
  • 6
  • 17

1 Answers1

0

Adding custom facts is what you're looking for. This serves the very purpose of storing persistent custom facts. For example, create the directory for the custom facts and display the variable ansible_local

    - name: Create directory for ansible custom facts
      ansible.builtin.file:
        state: directory
        recurse: true
        path: /etc/ansible/facts.d
    - debug:
        var: ansible_local

The variable ansible_local shall be an empty dictionary if you haven't configured custom facts before

  ansible_local: {}

Set the variables before_add and after_add, and display the difference

    - set_fact:
        before_add: "{{ ansible_local.devices.general.before_add|
                        default([]) }}"
        after_add: "{{ hostvars[inventory_hostname].ansible_devices.keys()|
                       select('string')|list }}"
    - debug:
        msg: "{{ after_add|difference(before_add) }}"

When you run the play for the first time the variable before_add will be an empty list and the debug task should display all devices, e.g.

  msg:
  - loop1
  - nvme0n1
    ...

Here comes the most important part of storing the persistent custom fact. For example, copy the dictionary into the file

    - name: Install custom devices fact
      ansible.builtin.copy:
        content: |
          {"general": {"before_add": {{ after_add }} }}
        dest: /etc/ansible/facts.d/devices.fact

When you run the play again setup should read ansible_local

  ansible_local:
    devices:
      general:
        before_add:
        - loop1
        - nvme0n1
          ...

and there shall be no difference between before_add and after_add

  msg: []

If you add a device the debug shall display the difference, e.g.

  msg:
  - sda

But, the difference will be empty if you remove the device. If you want to see both added and removed devices use symmetric_difference instead of difference, e.g.

    - debug:
        msg: "{{ after_add|symmetric_difference(before_add) }}"
Vladimir Botka
  • 3,791
  • 6
  • 17