'Compare two files with Ansible

I am struggling to find out how to compare two files. Tried several methods including this one which errors out with:

FAILED! => {"msg": "The module diff was not found in configured module paths. Additionally, core modules are missing. If this is a checkout, run 'git pull --rebase' to correct this problem."}

Is this the best practice to compare two files and ensure the contents are the same or is there a better way?

Thanks in advance.

My playbook:

- name: Find out if cluster management protocol is in use
      ios_command:
        commands:
          - show running-config | include ^line vty|transport input
      register: showcmpstatus
 - local_action: copy content="{{ showcmpstatus.stdout_lines[0] }}" dest=/poc/files/{{ inventory_hostname }}.result
    - local_action: diff /poc/files/{{ inventory_hostname }}.result /poc/files/transport.results
      failed_when: "diff.rc > 1"
      register: diff
 - name: debug output
      debug: msg="{{ diff.stdout }}"


Solution 1:[1]

your "diff" task is missing the shell keyword, Ansible thinks you want to use the diff module instead.

also i think diff (as name of the variable to register the tasks result) leads ansible to confusion, change to diff_result or something.

code (example):

  tasks:
  - local_action: shell diff /etc/hosts /etc/fstab
    failed_when: "diff_output.rc > 1"
    register: diff_output

  - debug:
      var: diff_output

hope it helps

Solution 2:[2]

A slightly shortened version of 'imjoseangel' answer which avoids setting facts:

  vars:
    file_1: cats.txt
    file_2: dogs.txt

  tasks:
  - name: register the first file
    stat:
      path: "{{ file_1 }}"
      checksum: sha1
      get_checksum: yes
    register: file_1_checksum

  - name: register the second file
    stat:
      path: "{{ file_2 }}"
      checksum: sha1
      get_checksum: yes
    register: file_2_checksum

  - name: Check if the files are the same
    debug: msg="The {{ file_1 }} and {{ file_2 }} are identical"
    failed_when: file_1_checksum.stat.checksum != file_2_checksum.stat.checksum
    ignore_errors: true

Solution 3:[3]

From Ansible User Guide: https://docs.ansible.com/ansible/latest/user_guide/playbooks_error_handling.html

- name: Fail task when both files are identical
  ansible.builtin.raw: diff foo/file1 bar/file2
  register: diff_cmd
  failed_when: diff_cmd.rc == 0 or diff_cmd.rc >= 2

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 lostsoulparty
Solution 3 user2514157