所有文件中的内容都没有在 ansible 中使用 grep 解析

contents in all files not parse using grep in ansible

我想解析两个不同文件中包含单词“harddisk”的行,例如 file1.txt 和 file2.txt。

使用下面的 ansible 命令只能获取 file2.txt 中的内容。请指教。

---

- name: find file name with .txt extension
  shell: find /root -name "file*.txt" -print
  register: "files"

- debug:
    var: files

- name: find word harddisk in the file contents and output to result.txt in the destination server.
  shell:  cat "{{ item }}" |grep -i 'harddisk' > /root/test/result.txt
  with_items:
    - "{{ files.stdout_lines }}"
  args:
     executable: /bin/bash
  register: output

给定文件列表

    my_files:
      - file1.txt
      - file2.txt

和内容

shell> cat file1.txt
foo
harddisk A
harddisk B
bar

shell> cat file2.txt
foo
harddisk C
harddisk D
bar

下面的任务 grep 文件中的行

    - shell: "cat {{ item }} | grep harddisk"
      register: files
      loop: "{{ my_files }}"

然后,下面的任务创建行列表

    - set_fact:
        my_list: "{{ files.results|
                     map(attribute='stdout_lines')|
                     list|flatten }}"
    - debug:
        var: my_list

给予

    "my_list": [
        "harddisk A",
        "harddisk B",
        "harddisk C",
        "harddisk D"
    ]

为了保留行的来源,下面的任务创建了一个包含数据的字典

    - set_fact:
        my_dict: "{{ dict(my_files|
                          zip(files.results|
                              map(attribute='stdout_lines')|
                              list)) }}"
    - debug:
        var: my_dict

给予

    "my_dict": {
        "file1.txt": [
            "harddisk A",
            "harddisk B"
        ],
        "file2.txt": [
            "harddisk C",
            "harddisk D"
        ]
    }