大家好,我正在使用 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: Get service status
command: systemctl is-active {{ config_vars.service_to_manage }}
register: service_status_before
changed_when: false
ignore_errors: true
- name: Debug service status
debug:
var: service_status_before.stdout
verbosity: 2
- name: Start service if not active
systemd:
name: "{{ config_vars.service_to_manage }}"
state: started
when: service_status_before.stdout != "active"
- name: Get service status after starting
command: systemctl is-active {{ config_vars.service_to_manage }}
register: service_status_after
changed_when: false
ignore_errors: true
- name: Display success message if service started
ansible.builtin.debug:
msg: "Table is ready for production. All steps succeeded successfully."
when: service_status_after.stdout == "active"
错误信息:
TASK [Get service status] ****************************************************************************
fatal: [10.6.20.150]: FAILED! => {"changed": false, "cmd": ["systemctl", "is-active", "dealer-tool"], "delta": "0:00:00.011135", "end": "2023-08-31 10:07:33.137622", "msg": "non-zero return code", "rc": 3, "start": "2023-08-31 10:07:33.126487", "stderr": "", "stderr_lines": [], "stdout": "inactive", "stdout_lines": ["inactive"]}
...ignoring
除了使用带有
command
的 command: systemctl is-active
模块来获取 service_fact
的错误方法之外,服务状态,根据 systemctl
退出状态 的文档,它将返回
3 "program is not running" unit is not active
如果设备未运行或未激活。因此,在这种情况下,另外定义失败是必要的
register: status
changed_when: false
failed_when: status.rc > 3
但是,为了简化和降低复杂性,并避免实现开箱即用的功能,建议收集
service_facts
,如Ansible:如何禁用但运行服务?或如何从 Ansible 传递变量service_facts
?.
进一步阅读