List comparison and list manipulation in Ansible
I keep saying time and time again that Ansible is not a programming language, it’s similar to one, it can do some programming things but ultimately it’s messy and I hate it BUT I can make it do some strange things.
List manipulation being one of those.
In this example I have two directories that I want to compare, directory one (/tmp/1) and directory two (/tmp/2). Directory one is the Source, that I want directory two to look like.
The use case is I want to sync /tmp/1 to /tmp/2 but you only want to remove the files in that are no longer /tmp/1, then you can sync (copy/template) the /tmp/1 directory knowing that nothing exists /tmp/2 that shouldn’t be there.
The ansible code is this with debug statements:
- hosts: local become: false tasks: - name: find 1 find: path=/tmp/1 register: one - debug: msg="{{ one }}" - name: find 2 find: path=/tmp/2 register: two - debug: msg="{{ item.path }}" with_items: - "{{ two.files }}" - set_fact: one_list: [] two_list: [] new_list: [] - name: append set_fact: one_list="{{ one_list }} + [ '{{ item.path | basename }}' ]" with_items: - "{{ one.files }}" - name: append set_fact: two_list="{{ two_list }} + [ '{{ item.path | basename }}' ]" with_items: - "{{ two.files }}" - debug: msg="{{ one_list }}" - debug: msg="{{ two_list }}" - set_fact: new_list="{{ two_list | difference(one_list) }}" - debug: msg="{{ new_list }}"
The final result is new_list is a list (array) that contains what needs to be removed from /tmp/2 to bring it in line with /tmp/1