本文介绍了Ansible:如何检查本地和远程文件集中的sha1校验和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我希望能够根据本地目录中的文件列表执行校验和.然后能够获取这些文件的校验和,并将其与远程系统上相同文件的校验和进行比较.
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}}"
推荐答案
您只需执行以下两项任务即可:(1)注册本地校验和,(2)检查远程校验和并将它们与相应的本地进行比较:
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 }}"
这篇关于Ansible:如何检查本地和远程文件集中的sha1校验和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!