使用Ansible更改服务文件时重启服务

时间:2019-08-20 10:36:26

标签: ansible ansible-template

我正在使用template模块创建一个systemd服务

---
- name: Systemd service
  template:
    src: sonar.unit.j2
    dest: /etc/systemd/system/sonarqube.service
  when: "ansible_service_mgr == 'systemd'" 

sonarqube.service的内容当然可以更改。更改后,我想重新启动服务。我该怎么办?

3 个答案:

答案 0 :(得分:2)

有两种解决方案。

注册+更改后

您可以注册template模块输出(状态更改),

register: service_conf

,然后使用when子句。

when: service_conf.changed

例如:

---
- name: Systemd service
  template:
    src: sonar.unit.j2
    dest: /etc/systemd/system/sonarqube.service
  when: "ansible_service_mgr == 'systemd'" 
  register: service_conf

- name: restart service
  service:
    name: sonarqube
    state: restarted
  when: service_conf.changed

处理程序+通知

您将重新启动服务任务定义为处理程序。然后在template任务中,notify处理程序。

tasks:
  - name: Add Sonarqube to Systemd service
    template:
      src: sonar.unit.j2
      dest: /etc/systemd/system/sonarqube.service
    when: "ansible_service_mgr == 'systemd'"
    notify: Restart Sonarqube
  - …

handlers:
  - name: Restart Sonarqube
    service:
      name: sonarqube
      state: restarted

更多信息in Ansible Doc

这2个之间的区别?

在第一种情况下,服务将直接重新启动。对于处理程序,重新启动将在播放结束时进行。

另一个区别是,如果您需要重新启动服务进行多项任务更改,则只需将notify添加到所有这些任务中即可。

  • 如果其中任何一项任务的状态更改,处理程序将运行。对于第一种解决方案,您将必须注册多个退货。它将生成更长的when子句_1 or子句_2 or
  • 即使多次通知,处理程序也只会运行一次。

答案 1 :(得分:1)

这需要处理程序

---
 - name: Testplaybook
   hosts: all
   handlers:
     - name: restart_service
       service:
         name: <servicename>
         state: restarted
   tasks:
     - template:
         src: ...
         dest: ...
       notify:
         - restart_service

当发生更改时,处理程序将自动由模块通知。有关handlers的更多信息,请参见文档。

答案 2 :(得分:1)

由于您使用的是systemd,因此您还需要执行daemon-reload,因为您更新了服务文件。

该任务只是将服务文件作为模板并通知处理程序:

- name: Systemd service
  template:
    src: sonar.unit.j2
    dest: /etc/systemd/system/sonarqube.service
  when: "ansible_service_mgr == 'systemd'" 
  notify: restart sonarqube systemd

基于上面特定的when子句的存在,我假设您可能想在不使用systemd的情况下指定单独的处理程序。 systemd案例的处理程序如下所示:

- name: restart sonarqube systemd
  systemd:
    name: sonarqube
    state: restarted
    daemon_reload: yes