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) }}"