使用 Ansible 停止可能不存在的服务

Mad*_*rin 6 ansible

我正在使用 Ansible 2.6.1

我试图确保某些服务没有在目标主机上运行。问题是该服务在某些主机上可能根本不存在。如果是这种情况,Ansible 由于缺少服务而失败并出现错误。服务由Systemd.

使用服务模块:

  - name: Stop service
    service:
      name: '{{ target_service }}'
      state: stopped
Run Code Online (Sandbox Code Playgroud)

因错误而失败 Could not find the requested service SERVICE: host

尝试使用命令模块:

 - name: Stop service
   command: service {{ target_service }} stop
Run Code Online (Sandbox Code Playgroud)

给出错误: Failed to stop SERVICE.service: Unit SERVICE.service not loaded.

我知道我可以使用,ignore_errors: yes但它也可能隐藏真正的错误。

另一种解决方案是有 2 个任务。一个检查服务是否存在,另一个只有在第一个任务找到服务但感觉很复杂时才运行。

如果服务不存在,是否有更简单的方法来确保服务停止并避免错误?

Naz*_*zar 9

我正在使用以下步骤:

- name: Get the list of services
  service_facts:

- name: Stop service
  systemd:
    name: <service_name_here>
    state: stopped
  when: "'<service_name_here>.service' in services"
Run Code Online (Sandbox Code Playgroud)

service_facts可以在收集事实阶段调用一次。


小智 7

与@ToughKernel 相同的解决方案,但用于systemd管理服务。

- name: disable ntpd service
  systemd:
    name: ntpd
    enabled: no
    state: stopped
  register: stop_service
  failed_when:
    - stop_service.failed == true
    - '"Could not find the requested service" not in stop_service.msg'
    # the order is important, only failed == true, there will be
    # attribute 'msg' in the result
Run Code Online (Sandbox Code Playgroud)


Tou*_*nel 6

以下将在中注册模块输出service_stop;如果模块执行的标准输出不包含"Could not find the requested service"并且服务无法根据返回代码停止,则模块执行将失败。由于您没有包含整个堆栈跟踪,我假设您发布的错误位于标准输出中,因此您可能需要根据错误进行稍微更改。

- name: Stop service
  register: service_stop
  failed_when: 
    - '"Could not find the requested service" not in service_stop.stdout'
    - service_stop.rc != 0
  service:
    name: '{{ target_service }}'
    state: stopped
Run Code Online (Sandbox Code Playgroud)