main.yml 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. - name: 'configure systemd unit {{ systemd_unit_name }}'
  2. copy:
  3. dest: '{{ _config_dir_path }}/{{ systemd_unit_name }}'
  4. content: |
  5. # ansible managed
  6. {{ systemd_unit_config }}
  7. mode: a=r
  8. vars: &copy_config_file_vars
  9. _config_dir_path: '/etc/systemd/{{ "user" if (systemd_unit_scope == "global") else systemd_unit_scope }}'
  10. register: _config_file
  11. when: systemd_unit_config is defined
  12. - name: 'create parent folder for drop-in config files of systemd unit {{ systemd_unit_name }}'
  13. file:
  14. path: '{{ _config_dir_path }}/{{ systemd_unit_name }}.d'
  15. state: directory
  16. mode: u=rwx,go=rx
  17. vars: *copy_config_file_vars
  18. register: _dropin_config_dir
  19. when: systemd_unit_dropin_config is defined
  20. - name: 'configure systemd unit {{ systemd_unit_name }} via drop-in config'
  21. copy:
  22. # > Along with a unit file foo.service, a "drop-in" directory foo.service.d/ may
  23. # > exist. All files with the suffix ".conf" from this directory will be parsed
  24. # > after the unit file itself is parsed.
  25. dest: '{{ _dropin_config_dir.path }}/{{ systemd_unit_dropin_config_name }}.conf'
  26. content: |
  27. # ansible managed
  28. {{ systemd_unit_dropin_config }}
  29. mode: a=r
  30. register: _dropin_config_file
  31. when: systemd_unit_dropin_config is defined
  32. - name: set return values
  33. set_fact:
  34. systemd_unit_config_changed: >-
  35. {{ _config_file.changed or _dropin_config_file.changed }}
  36. - name: 'fetch state of systemd unit {{ systemd_unit_name }}'
  37. systemd:
  38. name: '{{ systemd_unit_name }}'
  39. register: _unit
  40. when: systemd_unit_scope == 'system'
  41. and (systemd_unit_config_changed or systemd_unit_restart_if_active)
  42. - name: 'set state of systemd unit {{ systemd_unit_name }}'
  43. systemd:
  44. daemon_reload: '{{ systemd_unit_config_changed }}'
  45. name: '{{ systemd_unit_name }}'
  46. enabled: '{{ systemd_unit_enabled | default(omit) }}'
  47. # > `started'/`stopped' are idempotent actions [...]
  48. # > `restarted' will always bounce the service
  49. state: >-
  50. {{ "restarted" if (systemd_unit_state is not defined
  51. or systemd_unit_state != "stopped")
  52. and (systemd_unit_config_changed
  53. or systemd_unit_restart_if_active)
  54. and 'ActiveState' in _unit.status
  55. and _unit.status.ActiveState == "active"
  56. else systemd_unit_state | default(omit) }}
  57. when: >-
  58. systemd_unit_scope == 'system'
  59. and (systemd_unit_config_changed
  60. or systemd_unit_enabled is defined
  61. or systemd_unit_state is defined
  62. or (systemd_unit_restart_if_active
  63. and 'ActiveState' in _unit.status
  64. and _unit.status.ActiveState == "active")
  65. )