Ansible - diff module

Ansible does not have a module that can be used to compare files for differences. However, the stat module can be used to get the checksum of each file. 

Let's say /tmp/foo.txt and /tmp/bar.txt both contain "Hello World". 

---
- hosts: localhost
  tasks:
  - stat:
      path: /tmp/foo.txt
    register: foo

  - stat:
      path: /tmp/bar.txt
    register: bar

  - debug:
      var: foo.stat.checksum

  - debug:
      var: bar.stat.checksum
...

 

In this scenario, the checksum of both foo.txt and bar.txt should be indentical.

ok: [localhost] => {
    "foo.stat.checksum": "0a2e0508dfc05868388bc725a72cfe7d78b41e6d"
}

ok: [localhost] => {
    "bar.stat.checksum": "0a2e0508dfc05868388bc725a72cfe7d78b41e6d"
}

 

A when statement can then be used to do something when the checksums are the same or are different.

- fail:
    msg: /tmp/foo.txt is exactly the same as /tmp/bar.txt
  when: foo.stat.checksum == bar.stat.checksum

 

A limitation of this approach is that the actual differences between files will not be returned. For this reason, it might be better to use the shell module with the diff command.

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

 

Let's say foo.txt contains "Hello" and bar.txt contains "World". Outputing the "diff" variable in this example could return something like this.

fatal: [localhost]: FAILED! => {
  "changed": true,
  "cmd": "diff /tmp/foo.txt /tmp/bar.txt",
  "delta": "0:00:00.007027",
  "end": "2021-09-21 23:27:24.330548",
  "msg": "non-zero return code",
  "rc": 1,
  "start": "2021-09-21 23:27:24.323521",
  "stderr": "",
  "stderr_lines": [],
  "stdout": "1c1\n< Hello\n---\n> World",
  "stdout_lines": ["1c1", "< Hello", "---", "> World"]
}

 

You probably will only want to return the stdout_lines.

- debug:
    var: diff.stdout_lines

 

Which should return something like this.

ok: [localhost] => {
    "diff.stdout_lines": [
        "1c1",
        "< Hello",
        "---",
        "> World"
    ]
}

 



Add a Comment




We will never share your name or email with anyone. Enter your email if you would like to be notified when we respond to your comment.





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




Comments

Web design by yours truely - me, myself, and I   |   jeremy.canfield@freekb.net   |