45

I want to install a systemd service from a Jinja2 template. How do I do this?

Do I have to use copy module to copy the file to /lib/systemd/system and then use systemd module to enable it?

Is there a better way?

Chris
  • 6,914
  • 5
  • 54
  • 80
ATOzTOA
  • 34,814
  • 22
  • 96
  • 117

1 Answers1

68

I use the template module to install the .service file into the /etc/systemd/system. According to this digital ocean blog post /lib/systemd/system should be reserved for packages bundled with the OS itself, and third party services should be defined in /etc/systemd/system.

With ansible's systemd module I'd start the service with daemon_reload=yes.

Prior to Ansible 2.2: I do a systemctl daemon-reload afterward (can use an ansible handler for this if appropriate) to prod systemd to pick up the new file.

- name: install myservice systemd unit file
  template: src=myservice.j2 dest=/etc/systemd/system/myservice.service

- name: start myservice
  systemd: state=started name=myservice daemon_reload=yes


# For ansilble < 2.2 only
#- name: reload systemd unit configuration
#  command: systemctl daemon-reload
Peter Lyons
  • 142,938
  • 30
  • 279
  • 274
  • 1
    The post doesn't mandate that user modules should be in `/etc/systemd/system`, just suggested that it takes precedence. Normally when you do `systemctl enable`, it creates a symlink from `/lib/systemd/system` to `/etc/systemd/system`. – ATOzTOA Oct 18 '16 at 19:06
  • 9
    @ATOzTOA It is not good practice to install user files on `/lib`. It should be left for system packages. – admirabilis Sep 17 '17 at 09:58
  • 5
    This will reload the systemd daemon EVERY TIME the playbook is executed, which makes this solution non-idempotent. Ideally, you only want to reload the daemon IF the first task resulted in a change, so a handler would be a better option for idempotency. – Jaap Joris Vens Oct 14 '21 at 18:37
  • 2
    ... and don't forget to use handlers/notify – Ivailo Bardarov Feb 25 '22 at 14:23