如何打破 Ansible 中的“with_lines"循环? [英] How to break `with_lines` cycle in Ansible?

查看:35
本文介绍了如何打破 Ansible 中的“with_lines"循环?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在 Ansible 中使用以下处理程序:

I would like to use the following handler with Ansible:

- name: force ntp update
  shell: ntpdate {{item}}
  with_lines: /etc/ntpd.serverlist

但我希望它在第一次成功执行后结束执行(列表包含您可以尝试同步的 ntpd 服务器.一个就足够了).我该怎么做?

But I want it to end execution after the first successful execution (the list contains ntpd servers with which you can attempt to sync. One is enough). How would I do that?

推荐答案

这是一个非常有趣的情况.我没有亲自尝试过,但我想知道这样的事情是否可行:

That's a very interesting situation you have. I haven't tried this personally, but I wonder if something like this would work:

- name: force ntp update
  shell: ntpdate {{item}}
  with_lines: /etc/ntpd.serverlist
  register: ntp_result
  when: ntp_result is not defined or ntp_result.rc != 0
  ignore_errors: yes

因此,简而言之,每次调用 ntpdate 都应使用调用 ntpdate 的返回代码填充 ntp_result 变量.如果变量不存在(因为它不会在第一次迭代期间填充),或者如果 ntpdate 调用失败,when 子句然后确保循环继续(rc != 0).如果对 ntpdate 的任何调用确实返回错误,告诉 Ansible 忽略任何错误可确保它继续循环.

So in a nutshell, each call to ntpdate should populate the ntp_result variable with the return code of the call to ntpdate. The when clause then ensures the loop continues if the variable doesn't exist (as it wouldn't have been populated during the first iteration), or if the ntpdate call failed (rc != 0). Telling Ansible to ignore any errors ensures that it continues looping if any of the calls to ntpdate does return an error.

唯一真正的缺点是,如果对 ntpdate 的调用都没有成功,它不会直接通知您.但是,您可能可以按照以下方式执行此任务:

The only real downside to this is that it won't directly notify you if none of the calls to ntpdate succeed. However you can probably follow this task with something along the lines of:

- name: fail if ntpdate fails
  fail: msg="All calls to ntpdate failed"
  when: ntp_result.rc != 0

如果最后一次调用的结果是 ntpdate 的非零结果,则意味着它们都没有成功.

If the last call resulted in a non-zero result from ntpdate then it means none of them succeeded.

这篇关于如何打破 Ansible 中的“with_lines"循环?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆