Ansible Playbook重启consul-template失败及重试配置问题求助
问题:Ansible重启systemd服务时的重试逻辑错误解决
初始场景与错误
我有一段启动服务的Ansible Playbook:
- name: Start service systemd: daemon_reload: yes state: restarted name: "consul-template"
执行时出现D-Bus连接相关的错误,推测是竞态问题:
fatal: [unix://var/run/docker.sock]: FAILED! => { "changed": false, "invocation": { "module_args": { "daemon_reexec": false, "daemon_reload": true, "enabled": null, "force": null, "masked": null, "name": "consul-template", "no_block": false, "scope": null, "state": "restarted", "user": null } }, "msg": "Unable to restart service consul-template: Warning! D-Bus connection terminated.\nFailed to wait for response: Connection reset by peer\n" }
第一次修改及错误
为解决竞态问题添加重试逻辑,但误将systemd写成system模块:
- name: Start service system: daemon_reload: yes state: restarted name: "consul-template" register: consul_template_result until: consul_template_result is succeeded retries: 20 delay: 10
执行后出现条件判断错误:
fatal: [unix://var/run/docker.sock]: FAILED! => { "msg": "The conditional check 'consul_template_result is succeeded' failed. The error was: The 'failed' test expects a dictionary" }
第二次修改及错误
修正模块名称为systemd,但条件判断仍有问题:
- name: Start service systemd: daemon_reload: yes state: restarted name: "consul-template" register: consul_template_result until: not consul_template_result.failed retries: 20 delay: 10
执行后出现变量未定义错误:
fatal: [unix://var/run/docker.sock]: FAILED! => { "msg": "The conditional check 'not consul_template_result.failed' failed. The error was: error while evaluating conditional (not consul_template_result.failed): 'consul_template_result' is undefined" }
解决方案
问题根源有两个:一是模块名称拼写错误,二是首次执行失败时注册变量可能未初始化。正确的重试逻辑写法如下:
方案一:先判断变量是否存在再检查状态
- name: Restart consul-template service with retries systemd: daemon_reload: yes state: restarted name: "consul-template" register: consul_template_result until: consul_template_result is defined and consul_template_result is succeeded retries: 20 delay: 10
方案二:使用default默认值处理未定义情况
- name: Restart consul-template service with retries systemd: daemon_reload: yes state: restarted name: "consul-template" register: consul_template_result until: (consul_template_result | default({'failed': true})).failed == false retries: 20 delay: 10
说明
- 必须使用正确的
systemd模块,而非拼写错误的system模块,否则模块无法正常工作,注册变量也会失败 - 首次执行失败时,Ansible可能不会生成有效的注册变量,因此需要先判断变量是否已定义,或通过
default给变量设置默认值,避免"undefined"错误 - 重试逻辑会在遇到D-Bus连接中断这类临时故障时,每隔10秒重试一次,最多重试20次,直到服务重启成功
内容的提问来源于stack exchange,提问作者Zag Gol
相关产品推荐
相关产品推荐

