从 Ansible 剧本中的 find 命令打印值

Print value from find command in Ansible playbook

我有以下剧本:

  - name: Find files
    find:
     paths: "{{ ARCHIVE }}"
     patterns: "{{ item }}_*"
     file_type: directory
    register: files_matched
    with_items: "{{ bucket_with_items }}"

#  - debug:
#     var: files_matched

  - name: Remove directories
    file:
     path: "{{ item.files.path }}"
     state: absent
    with_items: "{{ files_matched.results }}"

但是当我执行此操作时,我收到以下错误消息:

fatal: [uwd-sschbn-01]: FAILED! => {"failed": true, "msg": "The task includes an option with an undefined variable. The error was: 'list object' has no attribute 'path'\n\nThe error appears to have been in '/etc/ansible/couchbase.yml': line 42, column 5, but may\nbe elsewhere in the file depending on the exact syntax problem.\n\nThe offending line appears to be:\n\n\n  - name: Remove directories\n   

我的情况是,我想删除存储在 'files_matched' 注册模块中的文件夹。但在此之前,我只想查看 files_matched 变量中存储的内容。我该怎么做?

因为你添加了一个with_itemsfiles_matched变成了这样的格式:

  "files_matched": {
        "changed": false, 
        "msg": "All items completed", 
        "results": [
            {
                "_ansible_ignore_errors": null, 
                "_ansible_item_result": true, 
                "_ansible_no_log": false, 
                "_ansible_parsed": true, 
                "changed": false, 
                "examined": 14, 
                "failed": false, 
                "files": [
                    {
                        "atime": 1526147209.0100496, 
                        "ctime": 1526147209.0100496, 
                        "dev": 43, 
                        "gid": 0, 

你会注意到现在有 files_matched.results,它有一个 "results" 的列表,其中包含你正在寻找的 files 变量。

您可以使用此 debug 任务打印您之前任务的结果:

  - debug: 
      msg: " value is  {{ item.files }} "
    with_items:
      - "{{ files_matched.results }}"

编辑

以上将显示上一个任务的注册变量的结果。要删除 files/directories,您需要在 set_fact 任务中解析 files_matched.results 以转换为列表,然后在另一个循环中处理它们(在您的情况下删除它们)。

示例:

  - name: get results in list
    set_fact:
      results_list: "{{ files_matched.results | map(attribute='files') | sum(start=[]) | map(attribute='path') | list }}"

  - name: print results
    debug:
      msg: "{{ item }}"
    with_items:
      - "{{ results_list }}"