如何使用 Ansible 停止服务 运行

How to stop a service if it is running using Ansible

我想知道仅当服务为 运行 时才在 Ansible 中停止服务的最佳方法。我希望按照这些思路做一些事情

- name: Check to see if Jenkins is running
  service:
    name: jenkins
    state: status
  register: jenkins_running_status

- name: Stop Jenkins if it is running
  service:
    name: jenkins
    state: stopped
  when: jenkins_running_status == False

显然这是行不通的。我想知道停止像 Jenkins 这样的服务的最佳方法,只要它是 运行。

无需检查服务是否为 运行。如果它是 运行,ansible 将停止它,如果不是,则什么也不会发生,因为状态已经停止。

因此,像这样的内容应该足以满足您的需求。

- name: Stop Jenkins
  service:
    name: jenkins
    state: stopped

但是,为了回答您的问题,类似这样的方法可行(我假设您使用的是 systemd):

- name: Check Jenkins
  shell: systemctl status jenkins.service | grep Active | awk -v N=2 '{print $N}'
  register: output

- name: Stop Jenkins
  service:
    name: jenkins
    state: stopped
  when: output.stdout == 'active'