在Ansible中使用循环直到结果不为空,可以使用until
循环结构和when
条件判断语句来实现。
以下是一个示例代码:
- name: Retry until result is not empty
hosts: localhost
gather_facts: false
tasks:
- name: Execute command and check result
shell: your_command_here
register: command_output
until: command_output.stdout is not empty
retries: 5
delay: 10
ignore_errors: true
when: command_output is undefined or command_output.stdout is empty
- name: Print command output
debug:
var: command_output.stdout
解释:
shell
任务中执行命令,并将输出结果注册到变量command_output
中。until
循环结构来判断command_output.stdout
是否为空,如果为空则重试。retries
参数为5,表示最多重试5次。delay
参数为10,表示每次重试的间隔时间为10秒。ignore_errors
参数为true,表示忽略命令执行的错误。when
条件判断语句来检查command_output
是否未定义或command_output.stdout
是否为空,如果是则执行循环。debug
任务中打印command_output.stdout
的值。这样,Ansible会循环执行命令,直到命令输出结果不为空为止。如果超过重试次数仍然为空,则任务会失败。
上一篇:Ansible循环与字典中的列表
下一篇:Ansible循环中出现无效数据