Ansible:循环两个register变量对比本地与远程文件校验和
修正Ansible Playbook中本地与远程文件校验和对比的错误
我来帮你搞定这个问题!你遇到的dict object has no element 0错误,核心原因是迭代方式不对,没办法把本地和远程的校验和结果一一配对。咱们一步步来修正:
原代码的问题根源
你在对比任务里用了with_items传入两个列表,Ansible会把这两个列表的元素单独迭代,而不是按索引一一配对。也就是说,每次循环的item只是local_files.results或remote_files.results里的单个结果字典,自然找不到item[0]和item[1]这两个索引。
修正后的完整Playbook
- name: Get cksum of files copied locally stat: path: "{{ item.src }}/{{ item.file }}" checksum_algorithm: sha1 delegate_to: localhost with_items: "{{ files }}" register: local_files - name: Get cksum of remote files stat: path: "{{ item.dest }}/{{ item.file }}_{{ item.package }}_NEW" checksum_algorithm: sha1 with_items: "{{ files }}" register: remote_files - name: Compare local and remote cksums. Fail if not matched debug: msg: "Checksum mismatch for file: {{ item.0.item.file }} (local: {{ item.0.stat.checksum }} | remote: {{ item.1.stat.checksum }})" failed_when: item.0.stat.checksum != item.1.stat.checksum with_together: - "{{ local_files.results }}" - "{{ remote_files.results }}"
关键修正细节
- 替换迭代模块:把
with_items改成with_together,这个模块会将两个列表的元素按索引一一配对,每次循环的item是一个包含两个元素的列表:[本地文件结果, 远程文件结果],用item.0和item.1就能分别访问两组结果。 - 优化错误提示:在
msg中加入文件名和两边的校验和值,方便你快速定位哪一个文件出现了不匹配的问题。 - 规范YAML语法:调整了
stat模块中path的空格格式,确保符合YAML的缩进规范(YAML对格式要求严格,多余空格可能引发隐性问题)。
验证逻辑说明
当with_together运行时,会依次将local_files.results[0]与remote_files.results[0]配对、local_files.results[1]与remote_files.results[1]配对……完全对应你定义的files列表里的每个文件,这样就能精准对比每个文件的本地与远程校验和了。
内容的提问来源于stack exchange,提问作者Jitu
相关产品推荐
相关产品推荐

