ansible / ansible-playbook版本:2.1.2.0 / 2.2.0.0
我正在尝试使用yum / apt安装软件包,但由于安装软件包的存储库位于packagecloud.io中,有时我收到一条错误消息(当我在运行我的ansible-playbook时传递-vvv
)。
[Errno 14] curl#56 - \"TCP connection reset by peer\"\nTrying other mirror. ...some ansible verbose text here.. [Errno 256] No more mirrors to try.
这不会一直发生。如果我再次重新运行相同的剧本,它工作正常,所以失败(连接重置)是随机的。
为了克服这个问题,我想使用Ansible的until
循环,我们必须使用register
变量。
所以,我通过引用Ansible doc来创建这个playbook动作,如何使用until
循环here,但是使用该语法我得到一个'字典'错误,说结果变量(已注册)dict没有任何名为stdout的键。然后我尝试使用result.rc(关键字段),它在CentOS机器上工作,但在Ubuntu 14.x可信赖的流浪汉机器上失败,结果如下.rc dict not present error:
- name: Install telegraf agent/collector (RedHat)
yum:
name: "{{ agent_collector }}"
state: "installed"
when: ( ansible_os_family == 'RedHat' and company_install_collector == true )
register: result
until: result.stdout.find("Installed:") != -1
#The following works in CentOS/RedHat
#until: result.rc == 0
- debug: msg="result (redhat) = {{ result }}"
或(更新我的问题很明显)
- name: Install Company Proxy (Ubuntu)
apt:
name: "{{ company_proxy_pkg }}"
state: "installed"
when: ( ansible_distribution == 'Ubuntu' and company_install_proxy == true )
register: result
until: result.rc == 0
- debug: msg="result (ubuntu) = {{ result }}"
获取以下错误消息(result.stdout - dict对象'在RedHat / CentOS和Ubuntu中都没有属性'stdout',但是获取dict对象只在Ubuntu服务器中没有属性'rc'):
fatal: [localhost]: FAILED! => {"failed": true, "msg": "The conditional check '(result.stdout.find(\"Installed:\") != -1)' failed. The error was: error while evaluating conditional ((result.stdout.find(\"Installed:\") != -1)): 'dict object' has no attribute 'stdout'"}
和
fatal: [localhost]: FAILED! => {
"failed": true,
"msg": "The conditional check 'result.rc == 0' failed. The error was: error while evaluating conditional (result.rc == 0): 'dict object' has no attribute 'rc'"
}
为什么寄存器变量(在我的情况下导致)没有stdout
或rc
dict / variables当文档说那些存在或者我可以在一个操作系统上的-vvv
详细输出中看到它们但是它没有显示在另一个操作系统上?
正确答案和调查结果:
yum
模块,如果由于connection reset
或其他原因失败。在这种情况下,可用于失败操作的唯一dict变量是result.rc!= 0.因此,在until
循环中,until: result.rc == 0
条件适用于CentOS的成功/失败情况。apt
模块操作成功,我得到result.stdout和result.stdout_lines变量设置但没有result.rc dict变量集。对于失败的操作,没有result.stout或result.stdout_lines或result.rc dict变量集。因此,在Ubuntu的情况下,我无法使用这些字典变量之一使用until
循环。我能想到的唯一解决方法是,将apt-get install <pacakge>
包装在一个脚本中,然后在BASH等中使用until循环来完成Ansible正在做的事情。至少,编码会更容易,如果退出代码不是0,那么我可以使用until
。
但是,我终于找到了一个解决方案,它可以在Ubuntu中用于成功和失败的情况:
因此,如果我必须使用注册变量when: result|failed
作为FAILED条件,然后使用result
,我将使用它(与失败状态相反),即:如下所示:Jinja2过滤器可能有帮助,即until
。
until: result|succeeded
好处是,上面的语句将适用于CentOS和Ubuntu以及成功/失败状态。
不推荐使用测试作为过滤器。而不是使用result|succeeded
使用result is succeeded
。此功能将在2.9版中删除。