![如何在 ansible 中正确使用循环中的预定义动态列表](https://linux22.com/image/758357/%E5%A6%82%E4%BD%95%E5%9C%A8%20ansible%20%E4%B8%AD%E6%AD%A3%E7%A1%AE%E4%BD%BF%E7%94%A8%E5%BE%AA%E7%8E%AF%E4%B8%AD%E7%9A%84%E9%A2%84%E5%AE%9A%E4%B9%89%E5%8A%A8%E6%80%81%E5%88%97%E8%A1%A8.png)
在剧本中,我需要使用动态列表中的循环,我写了这样的结构:
dirs:
- one
- two
- three
path_to_some_files:
- some_path/folder/{{ item }}/*.file
with_items:
- '{{ dirs }}'
但这并不正确。怎样写才更正确?
答案1
这取决于你想要实现什么。路径中的通配符表明你可能想要找到模式。例如,给定树
shell> tree some_path
some_path/
├── one
│ ├── A
│ └── A.file
├── three
│ ├── C
│ └── C.file
└── two
├── B
└── B.file
下面的剧本
- hosts: localhost
vars:
dirs:
- one
- two
- three
tasks:
- find:
paths: "some_path/{{ item }}"
patterns: "*.file"
register: result
loop: "{{ dirs }}"
- debug:
msg: "{{ result.results|json_query('[].files[].path') }}"
给出(节选)
msg:
- some_path/one/A.file
- some_path/two/B.file
- some_path/three/C.file
附注:在上面的例子中,循环不是必需的,因为参数路径模块寻找可以是列表。例如,以下任务给出相同的结果
- find:
paths: "{{ dirs }}"
patterns: "*.file"
register: result
vars:
dirs:
- some_path/one
- some_path/two
- some_path/three
- debug:
msg: "{{ result.files|json_query('[].path') }}"
答案2
静态列表
- name: create directory
file:
path: "some_path/folder/{{ item }}/*.file"
state: directory
loop:
- one
- two
- three
来自变量的列表
- name: create directory
file:
path: "some_path/folder/{{ item }}/*.file"
state: directory
loop: "{{ somelist }}"
https://docs.ansible.com/ansible/latest/user_guide/playbooks_loops.html#iterating-over-a-simple-list