如何使用 Ansible 2.x 不递归地遍历目录的目录
How to loop not recursively over directories of directory with Ansible 2.x
除此之外还有其他方法 不递归地 遍历 root_dir
:
目录的目录
- name: loop over directories
debug: var=item
with_filetree: "{{root_dir}}"
when: (item.path.split('/') | length == 1) and (item.state == 'directory')
因为这看起来很牵强,也许有更好的方法(不会在目录上深入循环)?
注意:我也尝试过 with_fileglob
和 item.state = 'directory'
的组合,但没有成功。
编辑:
- 使用 bash 命令,然后用 Ansible 解析它(如@techraf 在评论中提出的
find
,或 ls -l | grep '^d'
)也可以满足需求,但我问的更多使用不同于 shell
或 command
. 的 Ansible 模块
或者使用 command: find
和参数来限制搜索深度(当然,它们在 GNU 和 BSD 版本的 find
中有所不同)。
或者使用两个 Ansible 的原生 find
任务,都带有 recurse: false
:
第一个:在 root_dir
中加上 file_type: directory
第二个:用 paths: "{{ item }}"
循环第一个的结果
由于第二个任务中的循环,您最终会得到存储在层次结构中的结果,因此要访问扁平化结果,请使用以下模板(参见 ):
{{ second_task.results | sum(attribute='files', start=[]) | map(attribute='path') | list }}
您可以添加第三个 set_fact
任务以简化在后续任务中引用变量。
除此之外还有其他方法 不递归地 遍历 root_dir
:
- name: loop over directories
debug: var=item
with_filetree: "{{root_dir}}"
when: (item.path.split('/') | length == 1) and (item.state == 'directory')
因为这看起来很牵强,也许有更好的方法(不会在目录上深入循环)?
注意:我也尝试过 with_fileglob
和 item.state = 'directory'
的组合,但没有成功。
编辑:
- 使用 bash 命令,然后用 Ansible 解析它(如@techraf 在评论中提出的
find
,或ls -l | grep '^d'
)也可以满足需求,但我问的更多使用不同于shell
或command
. 的 Ansible 模块
或者使用 command: find
和参数来限制搜索深度(当然,它们在 GNU 和 BSD 版本的 find
中有所不同)。
或者使用两个 Ansible 的原生 find
任务,都带有 recurse: false
:
第一个:在
root_dir
中加上 第二个:用
paths: "{{ item }}"
循环第一个的结果
file_type: directory
由于第二个任务中的循环,您最终会得到存储在层次结构中的结果,因此要访问扁平化结果,请使用以下模板(参见
{{ second_task.results | sum(attribute='files', start=[]) | map(attribute='path') | list }}
您可以添加第三个 set_fact
任务以简化在后续任务中引用变量。