在Ansible中可以使用循环来创建模板并访问项。下面是一个使用循环创建多个文件模板的示例:
files.yml
,例如:files:
- name: file1.txt
content: "This is file 1."
- name: file2.txt
content: "This is file 2."
- name: file3.txt
content: "This is file 3."
create_files.yml
,其中包含创建文件模板的任务:---
- hosts: localhost
gather_facts: false
vars_files:
- files.yml
tasks:
- name: Create file templates
template:
src: templates/file_template.j2
dest: "{{ item.name }}"
loop: "{{ files }}"
file_template.j2
,例如:{{ item.content }}
在这个示例中,files
变量包含了多个文件的名称和内容。然后,在任务中使用循环将每个文件模板的内容写入对应的目标文件中。使用item.name
表示当前循环的文件名称,item.content
表示当前循环的文件内容。
通过运行这个Ansible Playbook,将会创建多个文件并将内容写入文件中。
注意:在运行这个示例之前,请确保已经安装了Ansible,并且在运行Playbook时具有适当的权限来创建文件。
上一篇:Ansible循环查找问题