2 Ansible task with Stat and include_vars

Viewed 186

wondering if anyone can help us with this.

The end goal is to refresh the variables back into the play from a YAML file which was generated previously if the file exists.

I'm using stat to check if the files exist and this works - 'name: Registering if file exists'. If i debug filecheck i can see the 2 entries in the dataset.

Next im trying to reload the vars from the file -final-dataset-file-1 if the file exists using the when condition - 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

This is the error i'm seeing

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"}

Its like we need to loop through filecheck for each file/item and match these against the files that are a part of the include_vars items but i'm not sure how to do this.

Any comments would be appreciated.

Cheers

1 Answers

Iterate the results from the previous task e.g.

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