在Ansible中循环遍历shell命令的输出可以使用with_items
或loop
模块。以下是一个示例:
---
- hosts: localhost
gather_facts: false
tasks:
- name: Execute shell command and loop through output
shell: ls /tmp
register: result
ignore_errors: true
- name: Loop through command output
debug:
msg: "{{ item }}"
loop: "{{ result.stdout_lines }}"
在上面的示例中,我们使用shell
模块执行ls /tmp
命令,并将输出结果保存到result
变量中。然后使用loop
模块循环遍历result.stdout_lines
,并将每行的内容打印出来。
另一种方法是使用with_items
模块,示例如下:
---
- hosts: localhost
gather_facts: false
tasks:
- name: Execute shell command and loop through output
shell: ls /tmp
register: result
ignore_errors: true
- name: Loop through command output
debug:
msg: "{{ item }}"
with_items: "{{ result.stdout_lines }}"
这里的操作和第一个示例类似,只是使用了with_items
模块来循环遍历输出。
无论是使用loop
还是with_items
,都可以在循环中访问每行输出的内容,可以根据需要进行进一步的处理或操作。
上一篇:Ansible循环遍历清单
下一篇:Ansible循环遍历文件中的项