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

1

5

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}}"
Rifkin answered 18/4, 2017 at 20:21 Comment(0)
L
10

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 }}"
Luis answered 19/4, 2017 at 6:12 Comment(1)
This worked like a charm!! the failed_when is very helpful. Thank you So much!!Rifkin

© 2022 - 2024 — McMap. All rights reserved.