如何在Ansible中遍历具有相对路径的目录和子目录列表?
我试图通过稍后在程序中将找到的路径重新用作变量来循环创建文件夹的过程。
这是用于在一个目录中创建每个目录的列表:
- find:
paths: /usr/local/foo/bar/
recurse: no
file_type: directory
register: find_result
我希望它为/ bar /
中的每个文件夹创建一个列表/ bar /中的每个子文件夹都包含一个名为alice,bob或charlie的子文件夹。例如:
/ usr / local / foo / bar / www / alice
/ usr / local / foo / bar / ww2 / bob
/ usr / local / foo / bar / ww3 / charlie
我为文件夹名称创建了一个列表:
FolderTypes:
source: {
- alice
- bob
- charlie
这是用于遍历每个爱丽丝,鲍勃或查理,并创建“ example”文件夹(如果尚不存在):
- file:
path: {{ item.path }}/{{ item.value }}/example
state: directory
owner: user
group: user
- with_items:
- "{{ find_result.directory }}"
- "{{ items.FolderTypes }}"
该程序用于保存找到的路径,循环遍历它们,并在其子目录中创建文件夹。尝试检查语法时出现错误:
ERROR! Syntax Error while loading YAML.
did not find expected key
The offending line appears to be:
- file:
path: {{ item.path }}/{{ item.value }}/example
^ here
We could be wrong, but this one looks like it might be an issue with
missing quotes. Always quote template expression brackets when they
start a value. For instance:
with_items:
- {{ foo }}
Should be written as:
with_items:
- "{{ foo }}"
答案 0 :(得分:0)
我认为您应该使用with_together而不是with_items
我认为您的剧本将是这样的:
- file:
path: {{ item[0].path }}/{{ item[1] }}/example
state: directory
owner: user
group: user
- with_items:
- "{{ find_result.directory }}"
- "{{ Types | list }}"
如果没有,可以进一步解释您的确切需求。
答案 1 :(得分:0)
您收到此错误消息是因为您在"
的开头忘记了path
。
您应该这样写(用with_together:
或with_nested:
(问题中不清楚)
- file:
path: "{{ item.path }}/{{ item.value }}/example"
state: directory
owner: user
group: user
- with_nested:
- "{{ find_result.directory }}"
- "{{ items.FolderTypes }}"
答案 2 :(得分:0)
如果您想操作本地(Ansible 控制器)主机中的文件,您可以使用 with_fileglob
示例:
- name: Copy each file over that matches the given pattern
copy:
src: "{{ item }}"
dest: "/etc/fooapp/"
owner: "root"
mode: 0600
with_fileglob:
- "/playbooks/files/fooapp/*"