要使用Ansible循环遍历文件中的项,可以使用with_items
关键字结合include_vars
模块或lookup
插件来实现。
下面是一种解决方法的示例代码:
- name: 循环遍历文件中的项
hosts: localhost
tasks:
- name: 读取文件内容
include_vars:
file: /path/to/file.yml
name: file_content
- name: 循环遍历文件中的项
debug:
msg: "{{ item }}"
loop: "{{ file_content }}"
在上述代码中,我们首先使用include_vars
模块读取文件的内容,并将其保存在变量file_content
中。然后,我们使用loop
关键字循环遍历file_content
变量,并使用debug
模块打印每个项的值。
如果文件中的项是一个列表,你也可以使用with_items
关键字结合lookup
插件来实现。以下是示例代码:
- name: 循环遍历文件中的项
hosts: localhost
tasks:
- name: 读取文件内容
set_fact:
file_content: "{{ lookup('file', '/path/to/file.txt').splitlines() }}"
- name: 循环遍历文件中的项
debug:
msg: "{{ item }}"
loop: "{{ file_content }}"
在上面的代码中,我们使用lookup
插件读取文件的内容,并使用splitlines()
方法将其拆分为一个列表。然后,我们使用loop
关键字循环遍历file_content
列表,并使用debug
模块打印每个项的值。
希望这个解决方法对你有所帮助!
下一篇:Ansible循环遍历字典