Bootstrap FreeKB - Ansible - Compare differences between files
Ansible - Compare differences between files

Updated:   |  Ansible articles

Ansible does not have a module that can be used to compare files for differences. However, the shell module with the diff command can be used. 

---
- hosts: localhost
  tasks:
  - shell: diff /tmp/foo.txt /tmp/bar.txt
    register: differences
    failed_when: differences.rc not in [ 0, 1 ]

  - debug:
      var: differences

  - debug:
      msg: differences were found between /tmp/foo.txt and /tmp/bar.txt
    when: differences.rc != 0
...

 

Let's say foo.txt contains "Hello" and bar.txt contains "World". Something like this should be returned.

TASK [debug] 
ok: [localhost] => {
    "differences": {
        "changed": true, 
        "cmd": "diff /tmp/foo.txt /tmp/bar.txt", 
        "delta": "0:00:00.005045", 
        "end": "2024-02-06 03:19:29.358270", 
        "failed": false, 
        "failed_when_result": false, 
        "msg": "non-zero return code", 
        "rc": 1, 
        "start": "2024-02-06 03:19:29.353225", 
        "stderr": "", 
        "stderr_lines": [], 
        "stdout": "1c1\n< Hello\n---\n> World", 
        "stdout_lines": [
            "1c1", 
            "< Hello", 
            "---", 
            "> World"
        ]
    }
}

TASK [debug] 
ok: [localhost] => {
    "msg": "differences were found between /tmp/foo.txt and /tmp/bar.txt"
}

 




Did you find this article helpful?

If so, consider buying me a coffee over at Buy Me A Coffee



Comments


Add a Comment


Please enter f3bc40 in the box below so that we can be sure you are a human.