Skip to content

Instantly share code, notes, and snippets.

@samuelharmer
Last active December 9, 2020 09:58
Show Gist options
  • Save samuelharmer/5cdc2d2365e31c3fe01a818dca928248 to your computer and use it in GitHub Desktop.
Save samuelharmer/5cdc2d2365e31c3fe01a818dca928248 to your computer and use it in GitHub Desktop.
Ansible Demo: Compare

Ansible Compare

Frequently we might need to make a change to a file and respond to removals as well as additions.

This playbook demonstrates how we can detect changes (using the Ansible host).

  1. Run the playbook in regular mode ansible-playbook demo-compare.yaml. Look for a file named demo-compare.txt alongside the playbook.
  2. Change a name in the file_data list.
  3. Re-run the playbook in --check mode.
  4. If any changes would be made (--check mode) or are made (regular mode) as a result, these are displayed by the final debug module.

Output (snippet)

TASK [debug] ******************************************************************
ok: [127.0.0.1] => {
      "msg": "removed: []\nadded: ['rudolph']\n"
}
---
- hosts: 127.0.0.1
vars:
file_data:
- dasher
- dancer
- prancer
- vixen
- comet
- cupid
- donder
# - rudolph
tasks:
- name: create a file with one name per line
copy:
dest: "{{ hostvars[inventory_hostname].playbook_dir }}/demo-compare.txt"
content: |
{% for thing in file_data %}{{ thing }}
{% endfor %}
diff: yes
register: file_result
- debug:
var: file_result
- when: file_result.changed
block:
- name: split the before and after variables into lines
set_fact:
file_lines_before: "{{ file_result.diff[0].before.split() }}"
file_lines_after: "{{ file_result.diff[0].after.split() }}"
- name: difference the lines both ways round
set_fact:
file_lines_removed: "{{ file_lines_before | difference(file_lines_after) }}"
file_lines_added: "{{ file_lines_after | difference(file_lines_before) }}"
- debug:
msg: |
removed: {{ file_lines_removed }}
added: {{ file_lines_added }}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment