首页 > 解决方案 > 从 Ansible playbook 中的 find 命令打印值

问题描述

我有以下剧本:

  - 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 变量中存储了什么。我怎样才能做到这一点?

标签: ansibleansible-facts

解决方案


它是因为你添加了一个with_items,所以files_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现在有一​​个“结果”列表,其中包含files您要查找的 var。

您可以使用此debug任务打印上一个任务的结果:

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

编辑

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

例子:

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

推荐阅读