Ansible用service模块重启httpd报无rc属性错误如何排查?
错误产生原因
- 核心原因有两个:
- 你使用的
service模块本身不会返回rc字段:rc是command、shell这类直接执行操作系统命令的模块特有的返回值,service作为Ansible封装的高阶模块,正常返回值仅包含changed、state、name等字段,不存在rc属性,直接调用自然会报错。 - 任务配置了
when: infrastructure_type == 'cloud'条件:如果该条件不满足,任务会直接进入跳过状态,此时你register注册的restart_status变量仅会包含skipped: true这一个属性,更不会存在rc字段,也会触发该报错。
- 你使用的
排查解决方法
- 第一步:修正
until重试判断逻辑
不要依赖特定模块的返回字段,直接使用Ansible通用的执行状态判断语法,将原until: restart_status.rc == 0替换为until: restart_status is succeeded,该语法适配所有Ansible模块的执行结果判断。
如果需要兼容任务跳过的场景,可以调整为until: restart_status is skipped or restart_status is succeeded,避免条件不命中时的判断报错。 - 第二步:(可选)确认任务触发状态
可以在当前任务后添加临时debug任务,打印restart_status的完整结构,确认返回字段和任务执行状态:- debug: var: restart_status - 修正后的完整任务代码参考:
--- - name: "Restart service httpd via service module" service: name: httpd state: restarted register: restart_status until: restart_status is skipped or restart_status is succeeded retries: 2 delay: 10 when: infrastructure_type == 'cloud' changed_when: restart_status.changed ignore_errors: yes
内容的提问来源于stack exchange,提问作者WhoAmI
相关产品推荐
相关产品推荐

