Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ansible: How to Check a local and remote set of files for sha1 checksum

I want to be able to do a checksum based on a list of files in a local dir. Then be able to get those files checksum and compare it to the checksum of the same files on a remote system.

I know I can get the with the following

# Local File
- stat:
   path: "{{ playbook_dir }}/roles/common/files/myfile.dat"
   checksum_algorithm: sha1
  delegate_to: localhost
  run_once: true
  register: localsha_result

# Remote file
- stat:
   path: "{{ rmt_dest_dir }}/myfile.dat"
   checksum_algorithm: sha1
  register: sha_result

and I have tried to loop through the files that I want to checksum with:

# Gather Files
- name: gather names of files
  local_action: shell  ls {{ playbook_dir }}/roles/common/files/*.dat | awk -F '/' '{ print $NF }'
  register: datfiles

# Local File 
- stat:
   path: "{{ playbook_dir }}/roles/common/files/{{ item }}"
   checksum_algorithm: sha1
  with_items: "{{ datfiles.stdout_lines }}"
  delegate_to: localhost
  run_once: true
  register: localsha_result

# Remote file
- stat:
   path: "{{ rmt_dest_dir }}/{{ item }}"
   checksum_algorithm: sha1
  with_items: "{{ datfiles.stdout_lines }}"
  register: sha_result

- name: check sha1
  fail: msg="SHA1 checksum fails"
  when: not sha_result.stat.checksum is defined or not sha_result.stat.checksum == "{{ item.stat.checksum }}"
with_items: "{{ datfiles.stdout_lines}}"
like image 817
Cale Avatar asked Jan 04 '23 03:01

Cale


1 Answers

You can do this with just two tasks: (1) register local checksums, (2) check remote checksums comparing them to corresponding local:

---
- hosts: test-server
  tasks:
    - stat:
        path: "{{ item }}"
        checksum_algorithm: sha1
      delegate_to: localhost
      with_fileglob: /tmp/*.dat
      register: local_files
    - stat:
        path: "/tmp/{{ item.stat.path | basename }}"
        checksum_algorithm: sha1
      failed_when: remote_files.stat.checksum != item.stat.checksum
      # failed_when condition checked after every iteration
      #   and remote_files here is a result of individual task
      #   but after loop is finished, remote_files is a cobination
      #   of all iterations results
      with_items: "{{ local_files.results }}"
      register: remote_files
      loop_control:
        label: "{{ item.stat.path | basename }}"
like image 185
Konstantin Suvorov Avatar answered Jan 17 '23 13:01

Konstantin Suvorov