2 带有 Stat 和 include_vars 的 Ansible 任务

问题描述

想知道是否有人可以帮助我们。

最终目标是将变量从之前生成的 YAML 文件刷新回播放,如果该文件存在。

我正在使用 stat 检查文件是否存在并且这有效 - “名称:如果文件存在则注册”。如果我调试文件检查,我可以看到数据集中的 2 个条目。

如果文件存在使用 when 条件 - filecheck.stat.exists

- name: Registering if file exists
  stat:
    path: "{{ inventory_dir }}/host_vars/{{ inventory_hostname }}/final-dataset-{{ item }}.yml"
  loop:
    - file-1
    - file-2
  register: filecheck

- name: IOS - Refreshing final-dataset variables generated by the above tasks in order to service any subsequent tasks
  include_vars:
    file: "{{ inventory_dir }}/host_vars/{{ inventory_hostname }}/final-dataset-{{ item }}.yml"
  loop:
    - file-1
    - file-2
  when: filecheck.stat.exists

这是我看到的错误

fatal: [router]: Failed! => {"msg": "The conditional check 'filecheck.stat.exists' Failed. The error was: error while evaluating conditional (filecheck.stat.exists): 'dict object' has no attribute 'stat'\n\nThe error appears to be in '/ansible/roles/roles_nane/tasks/report.yml': line 94,column 3,but may\nbe elsewhere in the file depending on the exact Syntax problem.\n\nThe offending line appears to be:\n\n\n- name: IOS - Refreshing final-dataset variables generated by the above tasks in order to service any subsequent tasks\n  ^ here\n"}

就像我们需要为每个文件/项目循环文件检查并将它们与作为 include_vars 项目一部分的文件进行匹配,但我不知道如何做到这一点。

如有任何意见,我们将不胜感激。

干杯

解决方法

迭代上一个任务的结果,例如

    - include_vars: "{{ item.stat.path }}"
      loop: "{{ filecheck.results }}"
      when: item.stat.exists