-
Notifications
You must be signed in to change notification settings - Fork 53
/
user.py
548 lines (487 loc) · 17.9 KB
/
user.py
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
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
#!/usr/bin/python
# -*- encoding: utf-8; py-indent-offset: 4 -*-
# Copyright: (c) 2023, Lars Getwan <lars.getwan@checkmk.com> &
# Marcel Arentz <gdspd_you@open-one.de> &
# Max Sickora <max.sickora@checkmk.com>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
DOCUMENTATION = r"""
---
module: user
short_description: Manage users in Checkmk.
# If this is part of a collection, you need to use semantic versioning,
# i.e. the version is of the form "2.5.0" and not "2.4".
version_added: "0.18.0"
description:
- Manage users in Checkmk.
extends_documentation_fragment: [checkmk.general.common]
options:
auth_type:
description:
- The authentication type.
Setting this to C(password) will create a normal user, C(automation) will create an automation user.
type: str
choices: [password, automation]
authorized_sites:
description: The names of the sites the user is authorized to access.
type: raw
contactgroups:
description: A list of contact groups assigned to the user.
type: raw
customer:
description:
- For the Checkmk Managed Edition (CME), you need to specify which customer ID this object belongs to.
type: str
disable_notifications:
description: Temporarily disable B(all) notifications for this user.
type: bool
disable_login:
description:
- If set to C(true), the user cannot log in anymore, but will remain part of the site.
Disabling a user does not affect notifications.
type: bool
disable_notifications_timerange:
description: The duration, for how log notifications should be disabled, if C(disable_notifications) is set to C(true).
type: dict
email:
description:
- The mail address of the user. Required if the user is a monitoring contact and should receive notifications via mail.
type: str
enforce_password_change:
description: If set to C(true), the user will be forced to change their password on the next login.
type: bool
fallback_contact:
description:
- This user will receive fallback notifications.
This means, if no notification rules match a certain event, they are sent to the fallback contacts.
type: bool
fullname:
description: A alias or the full name of the user.
type: str
idle_timeout_duration:
description: The duration in seconds, if C(idle_timeout_option) is set to C(individual).
type: int
idle_timeout_option:
description:
- Specify, whether the idle timeout should use the global configuration, use an individual duration or be disabled entirely.
type: str
choices: [global, disable, individual]
interface_theme:
description: The theme of the user interface.
type: str
choices: [default, dark, light]
language:
description:
- Configure the language to be used by the user in the user interface.
Omitting this will configure the default language.
type: str
choices: [default, en, de]
mega_menu_icons:
description:
- This option decides if colored icons should be shown for every entry in the mega menus
or only for the headlines (the 'topics').
type: str
choices: [topic, entry]
name:
description: The user you want to manage.
required: true
type: str
navigation_bar_icons:
description: This option decides if icons in the navigation bar should show/hide the respective titles.
type: str
choices: [hide, show]
pager:
description: A (mobile) phone number, used to receive e.g., SMS.
type: str
aliases: ["pager_address"]
password:
description:
- The password or secret for login. Depending on the C(auth_type), this is interpreted as a password or secret.
type: str
roles:
description: A list of roles assigned to the user.
type: raw
show_mode:
description:
- This option decides what show mode should be used for unvisited menus.
Alternatively, this option can also be used to enforce show more removing the three dots for all menus.
type: str
choices: [default, default_show_less, default_show_more, enforce_show_more]
sidebar_position:
description: The position of the sidebar.
type: str
choices: [left, right]
state:
description: The desired state.
type: str
default: present
choices: [present, absent, reset_password]
author:
- Lars Getwan (@lgetwan)
- Marcel Arentz (@godspeed-you)
- Max Sickora (@max-checkmk)
"""
EXAMPLES = r"""
# Create a user.
- name: "Create a user."
checkmk.general.user:
server_url: "http://myserver/"
site: "local"
automation_user: "myuser"
automation_secret: "mysecret"
name: "krichards"
fullname: "Keith Richards"
email: "keith.richards@rollingstones.com"
password: "Open-G"
contactgroups:
- "rolling_stones"
- "glimmer_twins"
- "x-pensive_winos"
- "potc_cast"
# Create an automation user.
- name: "Create an automation user."
checkmk.general.user:
server_url: "http://myserver/"
site: "local"
automation_user: "myuser"
automation_secret: "mysecret"
name: "registration"
fullname: "Registration User"
auth_type: "automation"
password: "ZGSDHUVDSKJHSDF"
roles:
- "registration"
state: "present"
# Create a user with the Checkmk Managed Edition (CME), using the `customer` parameter.
- name: "Create a user."
checkmk.general.user:
server_url: "http://myserver/"
site: "local"
automation_user: "myuser"
automation_secret: "mysecret"
name: "krichards"
fullname: "Keith Richards"
email: "keith.richards@rollingstones.com"
customer: "provider"
password: "Open-G"
contactgroups:
- "rolling_stones"
- "glimmer_twins"
- "x-pensive_winos"
- "potc_cast"
# Create a detailed user.
- name: "Create a more complex user."
checkmk.general.user:
server_url: "http://myserver/"
site: "local"
automation_user: "myuser"
automation_secret: "mysecret"
name: "horst"
fullname: "Horst Schlämmer"
customer: "provider"
auth_type: "password"
password: "uschi"
enforce_password_change: true
email: "checker@grevenbroich.de"
fallback_contact: true
pager: 089-123456789
contactgroups:
- "sport"
- "vereinsgeschehen"
- "lokalpolitik"
disable_notifications: true
disable_notifications_timerange: { "start_time": "2023-02-23T15:06:48+00:00", "end_time": "2023-02-23T16:06:48+00:00"}
language: "de"
roles:
- "user"
authorized_sites:
- "{{ mysite }}"
interface_theme: "dark"
sidebar_position: "right"
navigation_bar_icons: "show"
mega_menu_icons: "entry"
show_mode: "default_show_more"
state: "present"
"""
RETURN = r"""
# These are examples of possible return values, and in general should use other names for return values.
message:
description: The output message that the module generates. Contains the API response details in case of an error.
type: str
returned: always
sample: 'User created.'
"""
import json
from ansible.module_utils.basic import AnsibleModule
from ansible_collections.checkmk.general.plugins.module_utils.api import CheckmkAPI
from ansible_collections.checkmk.general.plugins.module_utils.types import RESULT
from ansible_collections.checkmk.general.plugins.module_utils.utils import (
result_as_dict,
)
USER = (
"username",
"fullname",
"customer",
"password",
"enforce_password_change",
"auth_type",
"disable_login",
"email",
"fallback_contact",
"pager",
"idle_timeout_option",
"idle_timeout_duration",
"roles",
"authorized_sites",
"contactgroups",
"disable_notifications",
"disable_notifications_timerange",
"language",
"interface_theme",
"sidebar_position",
"navigation_bar_icons",
"mega_menu_icons",
"show_mode",
)
class UserHTTPCodes:
# http_code: (changed, failed, "Message")
get = {
200: (False, False, "User found, nothing changed"),
404: (False, False, "User not found"),
}
create = {200: (True, False, "User created")}
edit = {200: (True, False, "User modified")}
delete = {204: (True, False, "User deleted")}
class UserEndpoints:
default = "/objects/user_config"
create = "/domain-types/user_config/collections/all"
class UserAPI(CheckmkAPI):
def _build_user_data(self):
user = {}
user["disable_notifications"] = {}
user["interface_options"] = {}
# For some keys the API has required sub keys. We can use them as indicator,
# that the key must be used
if self.required.get("auth_type"):
user["auth_option"] = {}
if self.required.get("email"):
user["contact_options"] = {}
if self.required.get("idle_timeout_option"):
user["idle_timeout"] = {}
for key, value in self.required.items():
if key in (
"username",
"fullname",
"customer",
"disable_login",
"roles",
"authorized_sites",
"contactgroups",
):
user[key] = value
if key in "pager":
key = "pager_address"
user[key] = value
if key in "language":
if value != "default":
user["language"] = value
if key in ("auth_type", "password", "enforce_password_change"):
if key == "password" and self.params.get("auth_type") == "automation":
# Unfortunately the API uses different strings for the password
# depending on the kind of user...
key = "secret"
user["auth_option"][key] = value
if key in ("email", "fallback_contact"):
user["contact_options"][key] = value
if key == "idle_timeout_option":
user["idle_timeout"]["option"] = value
if key == "idle_timeout_duration":
user["idle_timeout"]["duration"] = value
if key == "disable_notifications":
user["disable_notifications"]["disable"] = value
if key == "disable_notifications_timerange":
user["disable_notifications"]["timerange"] = value
if key in (
"interface_theme",
"sidebar_position",
"navigation_bar_icons",
"mega_menu_icons",
"show_mode",
):
user["interface_options"][key] = value
return user
def _set_current(self, result):
# A flat hierarchy allows an easy comparison of differences
content = json.loads(result.content)["extensions"]
for key in USER:
if key in content:
if key != "disable_notifications":
self.current[key] = content[key]
if key in "pager" and "pager_address" in content:
self.current[key] = content["pager_address"]
if key in ("email", "fallback_contact") and "contact_options" in content:
self.current[key] = content["contact_options"][key]
if key == "idle_timeout_option":
self.current[key] = content["idle_timeout"]["option"]
if key == "idle_timeout_duration":
if "duration" in content["idle_timeout"]:
self.current[key] = content["idle_timeout"]["duration"]
if key == "disable_notifications":
if "disable" in content["disable_notifications"]:
self.current[key] = content["disable_notifications"]["disable"]
else:
self.current[key] = False
if key == "disable_notifications_timerange":
if "timerange" in content["disable_notifications"]:
self.current[key] = content["disable_notifications"]["timerange"]
if (
key
in (
"interface_theme",
"sidebar_position",
"navigation_bar_icons",
"mega_menu_icons",
"show_mode",
)
and key in content["interface_options"]
):
self.current[key] = content["interface_options"][key]
def _build_default_endpoint(self):
return "%s/%s" % (UserEndpoints.default, self.params.get("name"))
def build_required(self):
# A flat hierarchy allows an easy comparison of differences
for key in USER:
if key == "username":
self.required[key] = self.params["name"]
continue
if self.params.get(key) is None:
continue
self.required[key] = self.params[key]
def needs_editing(self):
black_list = ("username", "password", "auth_type", "authorized_sites")
for key, value in self.required.items():
if key not in black_list and self.current.get(key) != value:
return True
return False
def get(self):
result = self._fetch(
code_mapping=UserHTTPCodes.get,
endpoint=self._build_default_endpoint(),
method="GET",
)
if result.http_code == 200:
self.state = "present"
self._set_current(result)
else:
self.state = "absent"
return result
def create(self):
data = self._build_user_data()
# It's allowed in Ansible to skip the fullname, but it's not allowed
# in the Checkmk API...
data.setdefault("fullname", data["username"])
result = self._fetch(
code_mapping=UserHTTPCodes.create,
endpoint=UserEndpoints.create,
data=data,
method="POST",
)
return result
def edit(self, etag):
data = self._build_user_data()
self.headers["if-Match"] = etag
result = self._fetch(
code_mapping=UserHTTPCodes.edit,
endpoint=self._build_default_endpoint(),
data=data,
method="PUT",
)
return result
def delete(self):
result = self._fetch(
code_mapping=UserHTTPCodes.delete,
endpoint=self._build_default_endpoint(),
method="DELETE",
)
return result
def run_module():
# define available arguments/parameters a user can pass to the module
module_args = dict(
server_url=dict(type="str", required=True),
site=dict(type="str", required=True),
validate_certs=dict(type="bool", required=False, default=True),
automation_user=dict(type="str", required=True),
automation_secret=dict(type="str", required=True, no_log=True),
name=dict(required=True, type="str"),
fullname=dict(type="str"),
customer=dict(type="str", required=False),
password=dict(type="str", no_log=True),
enforce_password_change=dict(type="bool", no_log=False),
auth_type=dict(type="str", choices=["password", "automation"]),
disable_login=dict(type="bool"),
email=dict(type="str"),
fallback_contact=dict(type="bool"),
pager=dict(type="str", aliases=["pager_address"]),
idle_timeout_duration=dict(type="int"),
idle_timeout_option=dict(
type="str", choices=["global", "disable", "individual"]
),
roles=dict(type="raw"),
authorized_sites=dict(type="raw"),
contactgroups=dict(type="raw"),
disable_notifications=dict(type="bool"),
disable_notifications_timerange=dict(type="dict"),
language=dict(type="str", choices=["default", "en", "de"]),
interface_theme=dict(type="str", choices=["default", "dark", "light"]),
sidebar_position=dict(type="str", choices=["left", "right"]),
navigation_bar_icons=dict(type="str", choices=["hide", "show"]),
mega_menu_icons=dict(type="str", choices=["topic", "entry"]),
show_mode=dict(
type="str",
choices=[
"default",
"default_show_less",
"default_show_more",
"enforce_show_more",
],
),
state=dict(
type="str",
default="present",
choices=["present", "absent", "reset_password"],
),
)
module = AnsibleModule(argument_spec=module_args, supports_check_mode=False)
# Use the parameters to initialize some common api variables
user = UserAPI(module)
user.build_required()
result = user.get()
etag = result.etag
required_state = user.params.get("state")
if user.state == "present":
if required_state == "reset_password":
user.required.pop("username")
result = user.edit(etag)
elif required_state == "absent":
result = user.delete()
elif user.needs_editing():
user.required.pop("username")
result = user.edit(etag)
elif user.state == "absent":
if required_state in "present":
result = user.create()
if required_state in "reset_password":
result = RESULT(
http_code=0,
msg="Can't reset the password for an absent user.",
content="",
etag="",
failed=False,
changed=False,
)
module.exit_json(**result_as_dict(result))
def main():
run_module()
if __name__ == "__main__":
main()