Ansible:使用with_items循环两个寄存器变量

时间:2018-05-25 06:48:28

标签: ansible

我已将本地和远程文件的校验和存储在两个不同的变量中。现在我想比较那些校验和,如果它们不匹配则失败。下面是代码。

   - name: Get cksum some 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 don't match"
    failed_when:  item[0].results.stat.checksum !=  item[1].results.stat.checksum
    with_items:
      - "{{ local_files.results }}"
      - "{{ remote_files.results }}"

当我运行时,我得到以下错误。

FAILED! => {"failed": true, "msg": "The conditional check 'item[0].results.stat.checksum !=  item[1].results.stat.checksum' failed. The error was: error while evaluating conditional (item[0].results.stat.checksum !=  item[1].results.stat.checksum): dict object has no element 0"}

如何更正它以比较校验和?

1 个答案:

答案 0 :(得分:1)

这样做:

- name: Get cksum some of files copied locally
  stat:
    path : "{{ item.src }}/{{ item.file }}"
  delegate_to: localhost
  with_items: "{{ files }}"
  register: local_files

- name: Get cksum of remote files 
  stat:
    path : "{{ item.dest }}/{{ item.file }}"
  with_items: "{{ files }}"
  register: remote_files

- name: Compare local and remote cksums. Fail if not matched
  fail:
    msg: "Checksum don't match"
  when:  item[0].stat.checksum != item[1].stat.checksum
  with_together:
    - "{{ local_files.results }}"
    - "{{ remote_files.results }}"