Browse Source

minimal ansible role configuring systemd unit

Fabian Peter Hammerle 3 years ago
commit
56850f8131
2 changed files with 47 additions and 0 deletions
  1. 18 0
      README.md
  2. 29 0
      tasks/main.yml

+ 18 - 0
README.md

@@ -0,0 +1,18 @@
+# Ansible Role: Systemd Unit
+
+## Required Variables
+
+```yaml
+systemd_unit_name: some.service
+systemd_unit_config: |
+  [Unit]
+  Description=...
+  # ...
+```
+
+## Optional Variables
+
+```yaml
+systemd_unit_state: started
+systemd_unit_enabled: yes
+```

+ 29 - 0
tasks/main.yml

@@ -0,0 +1,29 @@
+- name: 'configure systemd unit {{ systemd_unit_name }}'
+  copy:
+    dest: '/etc/systemd/system/{{ systemd_unit_name }}'
+    content: |
+      # ansible managed
+      {{ systemd_unit_config }}
+    mode: a=r
+  register: _config_file
+- name: 'fetch state of systemd unit {{ systemd_unit_name }}'
+  systemd:
+    name: '{{ systemd_unit_name }}'
+  register: _unit
+  when: _config_file.changed
+- name: 'set state of systemd unit {{ systemd_unit_name }}'
+  systemd:
+    daemon_reload: '{{ _config_file.changed }}'
+    name: '{{ systemd_unit_name }}'
+    enabled: '{{ systemd_unit_enabled | default(omit) }}'
+    state: >-
+      {{ "restarted" if (systemd_unit_state is not defined
+                            or systemd_unit_state != "stopped")
+                         and _config_file.changed
+                         and _unit.status.ActiveState == "active"
+         else systemd_unit_state | default(omit) }}
+  when: >-
+    _config_file.changed
+    or systemd_unit_enabled is defined
+    or systemd_unit_state is defined
+    or (_config_file.changed and systemd_unit.status.ActiveState == "active")