-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathunit_file.py
More file actions
427 lines (340 loc) · 11.4 KB
/
Copy pathunit_file.py
File metadata and controls
427 lines (340 loc) · 11.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
#!/usr/bin/python3
# -*- coding: utf-8 -*-
# (c) 2020-2023, Bodo Schulz <bodo@boone-schulz.de>
# Apache-2.0 (see LICENSE or https://opensource.org/license/apache-2-0)
# SPDX-License-Identifier: Apache-2.0
from __future__ import annotations
import os
import shutil
from ansible.module_utils.basic import AnsibleModule
from ansible_collections.bodsch.core.plugins.module_utils.checksum import Checksum
from ansible_collections.bodsch.core.plugins.module_utils.directory import (
create_directory,
)
# ---------------------------------------------------------------------------------------
DOCUMENTATION = """
module: unit_file
author:
- Bodo 'bodsch' Schulz (@bodsch)
short_description: Creates a systemd unit file.
version_added: 1.2.0
description:
- Creates a systemd unit file.
- The `service`, `timer` and `socket` types are supported.
options:
unit_type:
description:
- The unit type to be created.
- The (C(service), C(timer) and C(socket)) types are supported.
- Default is C(service).
type: str
choices: [ service, timer, socket ]
name:
description:
- The name of the unit file.
type: str
state:
description:
- Whether to install (C(present) or remove (C(absent) a unit file.
- Default is C(present).
type: str
choices: [ absent, present ]
drop_ins:
description:
- A list of possible systemd drop-ins.
- The structure corresponds exactly to that of a normal unit file.
type: list
unit_file:
description: The content of a systemd unit file.
type: dict
"""
EXAMPLES = """
- name: create getty drop-ins
bodsch.systemd.unit_file:
name: "getty@tty1"
state: "present"
unit_type: "service"
drop_ins:
- name: autologin
state: present
service:
ExecStart:
- ""
- "{% raw %}-/sbin/agetty -o '-p -f -- \\\\u' --noclear --autologin username %I $TERM{% endraw %}"
Type: simple
- name: noclear
state: absent
service:
TTYVTDisallocate: false
when:
- ansible_service_mgr == 'systemd'
- name: create systemd unit file
bodsch.systemd.unit_file:
name: "vaultwarden"
state: "present"
unit_type: "service"
unit_file:
description: |
#
#
#
#
#
#
Unit:
Description: Vaultwarden API server
Documentation: https://github.com/dani-garcia/vaultwarden
After: network.target
Service:
Type: simple
User: vaultwarden
Group: vaultwarden
LimitNOFILE: 1048576
UMask: "0077"
ExecStart: /usr/bin/vaultwarden
EnvironmentFile: /etc/vaultwarden/config.env
Install:
WantedBy: multi-user.target
when:
- ansible_service_mgr == 'systemd'
- name: create systemd socket
bodsch.systemd.unit_file:
name: "systemd-initctl"
state: "present"
unit_type: "socket"
unit_file:
description: |
# SPDX-License-Identifier: LGPL-2.1-or-later
#
# This file is part of systemd.
#
# systemd is free software; you can redistribute it and/or modify it
# under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation; either version 2.1 of the License, or
# (at your option) any later version.
unit:
Description: initctl Compatibility Named Pipe
Documentation: man:systemd-initctl.socket(8)
DefaultDependencies: no
Before: sockets.target
Socket:
ListenFIFO: /run/initctl
Symlinks: /dev/initctl
SocketMode: "0600"
when:
- ansible_service_mgr == 'systemd'
- name: create systemd timer
bodsch.systemd.unit_file:
name: "systemd-tmpfiles-clean"
state: "present"
unit_type: "timer"
unit_file:
unit:
Description: Daily Cleanup of Temporary Directories
Documentation: man:tmpfiles.d(5) man:systemd-tmpfiles(8)
ConditionPathExists: "!/etc/initrd-release"
timer:
OnBootSec: 15min
OnUnitActiveSec: 1d
when:
- ansible_service_mgr == 'systemd'
"""
RETURN = """
changed:
type: bool
description: Status of the action
msg:
type: str
description: Readable edition of what has been done.
"""
# --------------------------------------------------------------------------------------------------
UNIT_TPL = """# generated by ansible
{% if item.description is defined %}
{{ item.description }}
{% set _ = item.pop('description') %}
{% endif %}
{% for section, options in item.items() %}
[{{ section | capitalize }}]
{% for option, values in options.items() %}
{% if values is string or values is number %}
{{ option.ljust(34) }} = {{ values }}
{% else %}
{% for value in values %}
{{ option.ljust(34) }} = {{ value }}
{% endfor %}
{% endif %}
{% endfor %}
{% endfor %}
{#
#}
"""
class SystemdUnitFile(object):
""" """
module = None
def __init__(self, module):
""" """
self.module = module
self.unit_type = module.params.get("unit_type")
self.name = module.params.get("name")
self.state = module.params.get("state")
self.overwrite = module.params.get("overwrite")
self.drop_ins = module.params.get("drop_ins")
self.unit_file = module.params.get("unit_file")
self.tmp_directory = os.path.join(
"/run/.ansible", f"systemd_unit.{str(os.getpid())}"
)
def run(self):
""" """
result = dict(
rc=1,
failed=True,
changed=False,
)
self.checksum = Checksum(self.module)
if self.state == "absent":
result = self.clean_unit_files()
else:
result = self.create_unit_files()
if os.path.exists(self.tmp_directory):
shutil.rmtree(self.tmp_directory)
return result
def create_unit_files(self):
""" """
if isinstance(self.drop_ins, list) and len(self.drop_ins) > 0:
create_directory(directory=self.tmp_directory, mode="0750")
result = self.create_drop_in(self.drop_ins)
if isinstance(self.unit_file, dict) and len(self.unit_file) > 0:
create_directory(directory=self.tmp_directory, mode="0750")
result = self.create_unit_file(self.unit_file)
return result
def clean_unit_files(self):
""" """
if isinstance(self.drop_ins, list) and len(self.drop_ins) > 0:
service_name = f"/etc/systemd/system/{self.name}.d"
for drop_in in self.drop_ins:
name = drop_in.get("name")
state = drop_in.get("state", "present")
if state == "absent":
unit_file = os.path.join(service_name, f"{name}.conf")
result = self.__remove_unit(unit_file)
if isinstance(self.unit_file, dict) and len(self.unit_file) > 0:
unit_file = os.path.join(
"/lib/systemd/system", f"{self.name}.{self.unit_type}"
)
result = self.__remove_unit(unit_file)
return result
def create_drop_in(self, data):
""" """
service_name = f"/etc/systemd/system/{self.name}.d"
if not os.path.exists(service_name):
create_directory(service_name)
for drop_in in data:
name = drop_in.get("name")
state = drop_in.get("state", "present")
unit_file = os.path.join(service_name, f"{name}.conf")
file_temporary = os.path.join(self.tmp_directory, f"{name}.conf")
if state == "present":
file_temporary = os.path.join(self.tmp_directory, f"{name}.conf")
data = self.__template(drop_in)
with open(file_temporary, "w") as f:
f.write(data)
result = self.__changed(file_temporary, unit_file)
else:
result = self.__remove_unit(unit_file)
return result
def create_unit_file(self, data):
""" """
unit_file = os.path.join("/lib/systemd/system", f"{self.name}.{self.unit_type}")
file_temporary = os.path.join(
self.tmp_directory, f"{self.name}.{self.unit_type}"
)
if self.state == "present":
data = self.__template(data)
with open(file_temporary, "w") as f:
f.write(data)
result = self.__changed(file_temporary, unit_file)
else:
pass
result = dict(changed=False, failed=False)
return result
def __changed(self, file_temporary, unit_file):
""" """
old_checksum = self.checksum.checksum_from_file(unit_file)
new_checksum = self.checksum.checksum_from_file(file_temporary)
changed = not (new_checksum == old_checksum)
new_file = False
msg = "The unit-file has not been changed"
# self.module.log(msg=f" file_name {unit_file}")
# self.module.log(msg=f" file_temporary {file_temporary}")
# self.module.log(msg=f" old_checksum {old_checksum}")
# self.module.log(msg=f" new_checksum {new_checksum}")
# self.module.log(msg=f" changed {changed}")
if changed:
new_file = old_checksum is None
shutil.move(file_temporary, unit_file)
msg = "The unit-file was successfully changed"
if new_file:
msg = "The unit-file was successfully created"
result = dict(changed=changed, msg=msg)
return result
def __remove_unit(self, unit_file):
""" """
if os.path.exists(unit_file):
os.remove(unit_file)
result = dict(
changed=True,
failed=False,
msg="The unit-file was successfully removed.",
)
else:
result = dict(
changed=False,
failed=False,
msg="The unit-file has already been removed.",
)
return result
def __template(self, data):
""" """
# self.module.log(msg=f"__template({data} ({type(data)}))")
if isinstance(data, dict):
from jinja2 import Template
if data.get("name"):
_ = data.pop("name")
if data.get("state"):
_ = data.pop("state")
# self.module.log(msg=f"{data} ({type(data)})")
tm = Template(UNIT_TPL, trim_blocks=True, lstrip_blocks=True)
d = tm.render(item=data)
else:
d = None
return d
def main():
""" """
args = dict(
unit_type=dict(
choose=["service", "socket", "timer"], default="service", type="str"
),
name=dict(required=True, type="str"),
state=dict(
choose=[
"absent",
"present",
],
default="present",
type="str",
),
overwrite=dict(required=False, default=False, type="bool"),
drop_ins=dict(required=False, default=[], type=list),
unit_file=dict(required=False, default={}, type=dict),
)
module = AnsibleModule(
argument_spec=args,
supports_check_mode=False,
)
k = SystemdUnitFile(module)
result = k.run()
# module.log(msg=f"= result: {result}")
module.exit_json(**result)
# import module snippets
if __name__ == "__main__":
main()