如何在Ansible中打破

如何在Ansible中打破

本文介绍了如何在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变量.然后,when子句可确保如果变量不存在(因为在第一次迭代期间不会填充变量)或ntpdate调用失败(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`周期?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-19 11:46