Search code examples
linuxansibledevopsansible-2.xstat

Ansible > file compare with stat module: Need to check file has the same value or not


There is a file: test.txt on remote1 and remote2 which has version with date and these file contains are n't fixed.

$ cat test.txt
Release_P1.11_2017-08-02-094316
02/08/2017

I need to check:

  1. if file contains are same, then move on further tasks.
  2. if file contains are not same, then stop the tasks.
   ---
   - name: latest file check
     stat:
        path: /tmp/test.txt
        get_checksum: yes
     register: test_file_check

   - debug:
        var: test_file_check.stat.checksum

Now if file contains are same, checksum value are equal otherwise it doesn't have same. but I don't figure out the solution.


Solution

  • All you need is second time check and when condition

    - hosts: remote_1
      tasks:
        - name: first file check
          stat:
            path: /tmp/test.txt
            get_checksum: yes
          register: test_file_check_1
    
    ...........................................
    - hosts: remote_2
      tasks: 
        - name: next check
          stat:
            path: /tmp/test.txt
            get_checksum: yes
          register: test_file_check_2
    ...........................................
    
    - name: Block run only if file has no changes
      command: /bin/true
      when: test_file_check_1.stat.checksum == test_file_check_2.stat.checksum
    

    http://docs.ansible.com/ansible/latest/playbooks_conditionals.html