在剧本中,我需要使用动态列表中的循环,我写了这样的结构:
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