Ansible执行systemctl is-active返回inactive触发fatal错误求助
解决Ansible执行
systemctl is-active返回inactive时的Fatal提示问题 你的问题根源在于systemctl is-active命令在服务inactive时会返回rc=3,Ansible默认会将非0返回码标记为任务失败,ignore_errors: true只是让流程继续执行,但不会消除失败提示。以下是几种彻底解决的方案:
方案1:使用service_facts模块收集服务状态(最推荐)
直接通过Ansible内置模块收集服务事实,无需执行外部命令,完全避免返回码问题:
- name: Edit application.properties hosts: trainingShuttlesBJ # gather_facts: true tasks: - name: Read service name from config.yml include_vars: file: config.yml name: config_vars - name: Gather all service facts ansible.builtin.service_facts: - name: Start service if not active systemd: name: "{{ config_vars.service_to_manage }}" state: started when: ansible_facts.services["{{ config_vars.service_to_manage }}.service"].state != 'active' - name: Display success message if service is active ansible.builtin.debug: msg: "Table is ready for production. All steps succeeded successfully." when: ansible_facts.services["{{ config_vars.service_to_manage }}.service"].state == 'active'
方案2:自定义command模块的失败条件
如果你坚持使用systemctl is-active命令,可以通过failed_when指定仅在非预期返回码时标记失败。systemctl is-active的返回码规则:
- 0:服务active
- 3:服务inactive
这两个都是正常状态,仅当返回码为其他值(如1=failed、2=activating)时才判定为失败:
- name: Get service status command: systemctl is-active {{ config_vars.service_to_manage }} register: service_status_before changed_when: false # 仅当返回码不在[0,3]范围内时标记失败 failed_when: service_status_before.rc not in [0, 3] - name: Get service status after starting command: systemctl is-active {{ config_vars.service_to_manage }} register: service_status_after changed_when: false failed_when: service_status_after.rc not in [0, 3]
方案3:强制命令返回0码(不推荐)
通过shell命令追加|| true强制返回0,但会掩盖所有真实错误(如服务不存在、权限不足),仅作应急使用:
- name: Get service status shell: systemctl is-active {{ config_vars.service_to_manage }} || true register: service_status_before changed_when: false
内容的提问来源于stack exchange,提问作者Nico Muscat
相关产品推荐
相关产品推荐

