win_find失败! => {“ msg”:“'dict对象'没有属性'files'”}

时间:2019-08-01 14:04:42

标签: ansible

我正在尝试使用带有“路径”变量的win_find来查找临时文件(例如c:\ users \ public \ appdata \ local \ temp),但是当我将其传递给调试程序时,我会收到错误消息

"FAILED! => {"msg": "'dict object' has no attribute 'files'"}"

我尝试交换“ register”和“ with_items”行,但这似乎没有任何区别。

- hosts: windows-02
  vars:
    dir: \AppData\Local\Temp\
  tasks:
  - name: find user directories
    win_find:
      paths: c:\users
      recurce: yes
      file_type: directory
      get_checksum: no
    register: user_dir

  - name: debug 1
    debug:
      msg: "{{ item.path + dir }}"
    loop: "{{ user_dir.files }}"

  - name: find temp files
    win_find:
      paths: "{{ item.path + dir }}"
      recurce: yes
      hidden: yes
      get_checksum: no
    register: files_to_delete
    with_items: "{{ user_dir.files }}"

  - name: debug
    debug:
      msg: "{{ item }}"
    loop: "{{ files_to_delete.files }}"

  - name: remove
    win_file:
      path: "{{ item.path }}"
      state: absent
    with_items: "{{ files_to_delete.files }}"

我希望获得要删除的文件列表,该列表将传递到“ win_files”模块。相反,我收到错误消息

"FAILED! => {"msg": "'dict object' has no attribute 'files'"}"

2 个答案:

答案 0 :(得分:1)

win_find模块中有一个错字,它是递归:是 请找到下面的代码对我有用

---
 - name: Find files 
   win_find:
    paths: "{{paths}}"
    age: "{{duration}}"
   register: log_files

 - name: Delete the files 
   win_file:
    path: "{{item.path}}"
    state: absent
   with_items: "{{log_files.files}}"

files_to_delete也不会具有files_to_delete.files,因为它处于循环状态。它将具有files_to_delete.results

答案 1 :(得分:0)

因此,至少在我看来,win_find在使用“ when_items”时不返回文件。我通过创建路径列表并将其传递到模块的“ paths”参数中来解决此问题。

这是我的代码:

- hosts: "{{ host }}"
  vars:
    dir: \AppData\Local\Temp\
    temp_paths: []
    line_break: \n
  tasks:
  - name: find user directories
    win_find:
      paths: c:\users
      recurse: no
      file_type: directory
      get_checksum: no
    register: user_dir

  - name: debug 1
    debug:
      msg: "{{ item.path + dir }}"
    loop: "{{ user_dir.files }}"

  - name: set temp path
    set_fact: temp_paths="{{temp_paths + [ item.path + dir ] }}"
    when:  item.path != 'C:\\users\\Public'
    with_items: "{{ user_dir.files }}"

  - name: find temp files
    win_find:
      paths: "{{ temp_paths }}"
      recurse: True
      patterns: '*'
      hidden: False
      get_checksum: False
    register: files_to_delete
 #   ignore_errors: yes

  - name: debug
    debug:
      msg: "{{ item.path }}"
    loop: "{{ files_to_delete.files }}"

  - name: remove
    win_file:
      path: "{{ item.path }}"
      state: absent
    with_items: "{{ files_to_delete.files }}"