difference in two file using ansible module

Viewed 10615

I want to see if there is any changes in the file one present in local and other on the remote host. If there is any difference, it should be visible in screen what should be the best way to do this using Ansible

For example:

src : /tmp/abc.txt
dest : hostname:/tmp/cde.txt
4 Answers

You can also use check_mode: yes and diff: yes tasks options to show differences:

---
- hosts: localhost
  gather_facts: no

  tasks:
    - name: "Only show diff between test1.txt & test2.txt" 
      copy:
        src: /tmp/test2.txt
        dest: /tmp/test1.txt
      check_mode: yes
      diff: yes

Example:

# cat /tmp/test1.txt
test1

# cat /tmp/test2.txt
test1
test2

# ansible-playbook diff.yaml
PLAY [localhost] ***********************************************************************************************************************************

TASK [Only show diff between test1.txt & test2.txt] ************************************************************************************************
--- before: /tmp/test1.txt
+++ after: /tmp/test2.txt
@@ -1 +1,2 @@
 test1
+test2

changed: [localhost]

PLAY RECAP *****************************************************************************************************************************************
localhost                  : ok=1    changed=1    unreachable=0    failed=0

More information on check_mode & diff here.

This sounds like a task you can do with the debug module. Use diff to get the diff of both files. Register the output and use debug for display:

- name: Generate diff
  command: diff  /tmp/abc.txt  /tmp/def.txt
  register: diff_result

- name: Show diff result
  debug:
    var: diff_result

From the command line,

ansible <host-pattern> -m copy -CD -a "src=<your local file> dest=<remote file or location>"

The -m copy option causes Ansible to invoke the copy module

The -C option causes Ansible to Check whether a change would occur, rather than perform the copy

The -D option causes Ansible to report what changes would occur if the copy were to be made

Output is similar to what the UNIX diff command produces, only this reports differences between a local file and remote copies.

---
- hosts: localhost
  gather_facts: yes
  become: yes
  become_method: sudo
  tasks:
   - name: Get ansible date/time facts
     setup:
       filter: "ansible_date_time"
       gather_subset: "!all"

   - name: Store DTG as fact
     set_fact:
       DTG: "{{ ansible_date_time.date }}"

   - name: Changes of the USCORE_Switch
     copy:
       src: /home/thilan_widearea_cloud/network-programmability/curentconfig/backups/{{hostvars.localhost.DTG}}/USNYCL3SW-{{hostvars.localhost.DTG}}-config.txt
       dest: /home/thilan_widearea_cloud/network-programmability/curentconfig/USBaseconfig.txt
     check_mode: yes
     diff: yes
     register: output
Related