【问题标题】:Ansible - Iterate Thru Folders Containing Files. Output to fileAnsible - 遍历包含文件的文件夹。输出到文件
【发布时间】:2017-11-22 02:29:00
【问题描述】:

希望有人可以为我提供答案。我目前有这样的文件夹结构。

/BASE_DIR
    /FOLDER_A
       - file1.txt
       - file2.txt
    /FOLDER_B
    /FOLDER_C
       - file3.txt

我正在尝试创建一个可以告诉我哪些文件夹包含文件的剧本。我的最终目标是拥有一个包含以下内容的平面文件:

FOLDER_A, file1.txt
FOLDER_A, file2.txt
FOLDER_C, file3.txt

这是我目前的剧本:

- name: get files from all folders
  shell: cd /BASE_DIR/{{ item.name }} && ls -p | grep -v / |grep .txt |cat
  with_items:
     - name: "FOLDER_A"
     - name: "FOLDER_B"
     - name: "FOLDER_C"
  register: "fileitems"

- name: combine to have folder name as key, filenames as values
  set_fact:
     folders_with_files: "{{ folders_with_files|default({}) | combine( { item.item.name: item.stdout_lines } ) }}"
  with_items: "{{ fileitems.results }}"
  when: "{{ item.stdout_lines|length }} > 0"

- debug:
  var: folders_with_files

我认为我可以遍历每个文件夹以查找 *.txt,然后使用组合,这将是一种简单的迭代方法。

ok: [localhost] => {
    "folders_with_files": {
        "FOLDER_A": [
            "file1.txt",
            "file2.txt"
        ],
        "FOLDER_C": [
            "file3.txt"
        ]
    }
}

但即使有这个输出,我认为我不能按照我需要的方式正确解析它。我认为嵌套循环可能会有所帮助,但这意味着我需要事先知道键的名称。

任何帮助将不胜感激!

谢谢, T

【问题讨论】:

  • 您确定为您的任务选择了正确的工具吗?
  • @techraf - 是的。我知道这可以在 shell 脚本中轻松解决。但这是一个更大的剧本的一部分,我希望看看 Ansible 是否可以自己解决这个问题。从我的回答来看,它可以,只是不像其他替代方案那么容易。

标签: ansible ansible-2.x


【解决方案1】:

我一发布问题就去想,我找到了自己的答案......

我决定删除组合并仅追加到一个空列表。

- set_fact:
 folders_with_files: []

- name: get all sql from each adapter
  shell: cd /tmp/{{ item.name }} && ls -p | grep -v / |grep .txt |cat
  with_items:
    - name: "FOLDER_A"
    - name: "FOLDER_B"
    - name: "FOLDER_C"
  register: "fileitems"

- name: combine to display which adapters have files
  set_fact:
    folders_with_files: "{{ folders_with_files + [{ 'name': item.item.name, 'files': item.stdout_lines }] }}"
  with_items: "{{ fileitems.results }}"
  when: "{{ item.stdout_lines|length }} > 0"

- debug:
    var: folders_with_files

然后我的输出变成了:

ok: [localhost] => {
    "folders_with_files": [
        {
            "files": [
                "file1.txt",
                "file2.txt"
            ],
            "name": "FOLDER_A"
        },
        {
            "files": [
                "file3.txt"
            ],
            "name": "FOLDER_C"
        }
    ]
}

然后我可以使用 with_subelements:

- name: echo
  shell: echo "{{ item.0.name }}, {{ item.1}}" >> /tmp/output.txt
  with_subelements:
     - "{{ folders_with_files }}"
     - files

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-03
    • 2023-03-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-20
    相关资源
    最近更新 更多