使用 Ansible 停止可能不存在的服务 [英] Using Ansible to stop service that might not exist

查看:34
本文介绍了使用 Ansible 停止可能不存在的服务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的是 Ansible 2.6.1.

I am using Ansible 2.6.1.

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

I am trying to ensure that certain service is not running on target hosts. Problem is that the service might not exist at all on some hosts. If this is the case Ansible fails with error because of missing service. Services are run by Systemd.

使用服务模块:

  - name: Stop service
    service:
      name: '{{ target_service }}'
      state: stopped

失败并出现错误找不到请求的服务SERVICE:主机

尝试使用命令模块:

 - name: Stop service
   command: service {{ target_service }} stop

出现错误:无法停止SERVICE.service:未加载单元SERVICE.service.

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

I know I could use ignore_errors: yes but it might hide real errors too.

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

An other solution would be having 2 tasks. One checking for existance of service and other that is run only when first task found service but feels complex.

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

Is there simpler way to ensure that service is stopped and avoid errors if the service does not exists?

推荐答案

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

The following will register the module output in service_stop; if the module execution's standard output does not contain "Could not find the requested service" AND the service fails to stop based on return code, the module execution will fail. Since you did not include the entire stack trace I am assuming the error you posted is in the standard output, you may need to change slightly based on your error.

- 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

这篇关于使用 Ansible 停止可能不存在的服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆