-
Notifications
You must be signed in to change notification settings - Fork 57
/
host_group.py
542 lines (446 loc) · 16.4 KB
/
host_group.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
#!/usr/bin/python
# -*- encoding: utf-8; py-indent-offset: 4 -*-
# Copyright: (c) 2022, Michael Sekania &
# Robin Gierse <robin.gierse@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: host_group
short_description: Manage host groups in Checkmk (bulk version).
# 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.11.0"
description:
- Manage host groups in Checkmk.
extends_documentation_fragment: [checkmk.general.common]
options:
name:
description: The name of the host group to be created/modified/deleted.
type: str
title:
description: The title (alias) of your host group. If omitted defaults to the name.
type: str
customer:
description: For the Checkmk Managed Edition (CME), you need to specify which customer ID this object belongs to.
required: false
type: str
groups:
description:
- instead of 'name', 'title' a list of dicts with elements of host group name and title (alias) to be created/modified/deleted.
If title is omitted in entry, it defaults to the host group name.
default: []
type: raw
state:
description: The state of your host group.
type: str
default: present
choices: [present, absent]
author:
- Michael Sekania (@msekania)
"""
EXAMPLES = r"""
# Create a single host group.
- name: "Create a single host group."
checkmk.general.host_group:
server_url: "http://myserver/"
site: "mysite"
automation_user: "myuser"
automation_secret: "mysecret"
name: "my_host_group"
title: "My Host Group"
customer: "provider"
state: "present"
# Create several host groups.
- name: "Create several host groups."
checkmk.general.host_group:
server_url: "http://myserver/"
site: "mysite"
automation_user: "myuser"
automation_secret: "mysecret"
customer: "provider"
groups:
- name: "my_host_group_one"
title: "My Host Group One"
- name: "my_host_group_two"
title: "My Host Group Two"
- name: "my_host_group_test"
title: "My Test"
state: "present"
# Create several host groups.
- name: "Create several host groups."
checkmk.general.host_group:
server_url: "http://myserver/"
site: "mysite"
automation_user: "myuser"
automation_secret: "mysecret"
customer: "provider"
groups:
- name: "my_host_group_one"
title: "My Host Group One"
- name: "my_host_group_two"
- name: "my_host_group_test"
state: "present"
# Delete a single host group.
- name: "Delete a single host group."
checkmk.general.host_group:
server_url: "http://myserver/"
site: "mysite"
automation_user: "myuser"
automation_secret: "mysecret"
name: "my_host_group"
state: "absent"
# Delete several host groups.
- name: "Delete several host groups."
checkmk.general.host_group:
server_url: "http://myserver/"
site: "mysite"
automation_user: "myuser"
automation_secret: "mysecret"
groups:
- name: "my_host_group_one"
- name: "my_host_group_two"
state: "absent"
"""
RETURN = r"""
message:
description: The output message that the module generates.
type: str
returned: always
sample: 'Host group created.'
"""
import json
# https://docs.ansible.com/ansible/latest/dev_guide/testing/sanity/import.html
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.urls import fetch_url
def exit_failed(module, msg):
result = {"msg": msg, "changed": False, "failed": True}
module.fail_json(**result)
def exit_changed(module, msg):
result = {"msg": msg, "changed": True, "failed": False}
module.exit_json(**result)
def exit_ok(module, msg):
result = {"msg": msg, "changed": False, "failed": False}
module.exit_json(**result)
def get_current_single_host_group(module, base_url, headers):
current_state = "unknown"
current_title = ""
etag = ""
name = module.params["name"]
api_endpoint = "/objects/host_group_config/" + name
url = base_url + api_endpoint
response, info = fetch_url(module, url, data=None, headers=headers, method="GET")
if info["status"] == 200:
body = json.loads(response.read())
current_state = "present"
etag = info.get("etag", "")
current_title = body.get("title", name)
elif info["status"] == 404:
current_state = "absent"
else:
exit_failed(
module,
"Error calling API. HTTP code %d. Details: %s"
% (info["status"], info.get("body", "N/A")),
)
return current_state, current_title, etag
def get_current_host_groups(module, base_url, headers):
current_groups = []
api_endpoint = "/domain-types/host_group_config/collections/all"
url = base_url + api_endpoint
response, info = fetch_url(module, url, headers=headers, method="GET")
if info["status"] == 200:
body = json.loads(response.read())
tmp = body.get("value", [])
# Response from 2.2.0 is different. So this should fix it until module is migrated to new CheckMKAPI
for el in tmp:
if el.get("domainType") == "host_group_config": # 2.2.0
current_groups = [
{
"name": el.get("id"),
"title": el.get("title", el.get("name")),
}
for el in tmp
]
else: # 2.0.0 and 2.1.0
current_groups = [
{
"name": el.get("href").rsplit("/", 1)[-1],
"title": el.get("title", el.get("name")),
}
for el in tmp
]
else:
exit_failed(
module,
"Error calling API in (collections). HTTP code %d. Details: %s"
% (info["status"], info.get("body", "N/A")),
)
return current_groups
def update_single_host_group(module, base_url, headers):
name = module.params["name"]
api_endpoint = "/objects/host_group_config/" + name
params = {
"alias": module.params.get("title", name),
}
url = base_url + api_endpoint
response, info = fetch_url(
module, url, module.jsonify(params), headers=headers, method="PUT"
)
if info["status"] != 200:
exit_failed(
module,
"Error calling API. HTTP code %d. Details: %s, "
% (info["status"], info["body"]),
)
def update_host_groups(module, base_url, groups, headers):
api_endpoint = "/domain-types/host_group_config/actions/bulk-update/invoke"
params = {
"entries": [
{
"name": el.get("name"),
"attributes": {
"alias": el.get("title", el.get("name")),
},
}
for el in groups
],
}
url = base_url + api_endpoint
response, info = fetch_url(
module, url, module.jsonify(params), headers=headers, method="PUT"
)
if info["status"] != 200:
exit_failed(
module,
"Error calling API (bulk-update). HTTP code %d. Details: %s, "
% (info["status"], info["body"]),
)
def create_single_host_group(module, base_url, headers):
name = module.params["name"]
api_endpoint = "/domain-types/host_group_config/collections/all"
if module.params.get("customer") is not None:
params = {
"name": name,
"alias": module.params.get("title", name),
"customer": module.params.get("customer", "provider"),
}
else:
params = {
"name": name,
"alias": module.params.get("title", name),
}
url = base_url + api_endpoint
response, info = fetch_url(
module, url, module.jsonify(params), headers=headers, method="POST"
)
if info["status"] != 200:
exit_failed(
module,
"Error calling API. HTTP code %d. Details: %s, "
% (info["status"], info["body"]),
)
def create_host_groups(module, base_url, groups, headers):
api_endpoint = "/domain-types/host_group_config/actions/bulk-create/invoke"
if module.params.get("customer") is not None:
params = {
"entries": [
{
"name": el.get("name"),
"alias": el.get("title", el.get("name")),
"customer": module.params.get("customer"),
}
for el in groups
],
}
else:
params = {
"entries": [
{
"name": el.get("name"),
"alias": el.get("title", el.get("name")),
}
for el in groups
],
}
url = base_url + api_endpoint
response, info = fetch_url(
module, url, module.jsonify(params), headers=headers, method="POST"
)
if info["status"] != 200:
exit_failed(
module,
"Error calling API (bulk-create). HTTP code %d. Details: %s, "
% (info["status"], info["body"]),
)
def delete_single_host_group(module, base_url, headers):
api_endpoint = "/objects/host_group_config/" + module.params["name"]
url = base_url + api_endpoint
response, info = fetch_url(module, url, data=None, headers=headers, method="DELETE")
if info["status"] != 204:
exit_failed(
module,
"Error calling API. HTTP code %d. Details: %s, "
% (info["status"], info["body"]),
)
def delete_host_groups(module, base_url, groups, headers):
api_endpoint = "/domain-types/host_group_config/actions/bulk-delete/invoke"
params = {
"entries": [el["name"] for el in groups],
}
url = base_url + api_endpoint
response, info = fetch_url(
module, url, module.jsonify(params), headers=headers, method="POST"
)
if info["status"] != 204:
exit_failed(
module,
"Error calling API (bulk-delete). HTTP code %d. Details: %s, "
% (info["status"], info["body"]),
)
def run_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(
type="str",
required=False,
),
title=dict(type="str", required=False),
customer=dict(type="str", required=False),
groups=dict(
type="raw",
required=False,
default=[],
),
state=dict(type="str", default="present", choices=["present", "absent"]),
)
module = AnsibleModule(
argument_spec=module_args,
mutually_exclusive=[
("groups", "name"),
],
required_one_of=[
("groups", "name"),
],
supports_check_mode=False,
)
# Use the parameters to initialize some common variables
headers = {
"Accept": "application/json",
"Content-Type": "application/json",
"Authorization": "Bearer %s %s"
% (
module.params.get("automation_user", ""),
module.params.get("automation_secret", ""),
),
}
base_url = "%s/%s/check_mk/api/1.0" % (
module.params.get("server_url", ""),
module.params.get("site", ""),
)
# Determine desired state
state = module.params.get("state", "present")
if (
"groups" in module.params
and module.params.get("groups")
and len(module.params.get("groups", [])) > 0
):
if "title" in module.params and module.params.get("title", ""):
exit_failed(
module,
"'title' has only effect when 'name' is defined and not 'groups'",
)
groups = module.params.get("groups")
# Determine which host groups do already exist
current_groups = get_current_host_groups(module, base_url, headers)
# Determine intersection and difference with input, according to 'name' only
if len(set([el.get("name") for el in groups])) != len(groups):
exit_failed(module, "two or more entries with the same name!")
listofnames = set([el.get("name") for el in current_groups])
intersection_list = [el for el in groups if el.get("name") in listofnames]
difference_list = [el for el in groups if not el.get("name") in listofnames]
# Handle the host group accordingly to above findings and desired state
if state == "present":
# create host groups which do not exist (difference)
# update host groups that exist (intersection)
msg_tokens = []
if len(difference_list) > 0:
create_host_groups(module, base_url, difference_list, headers)
msg_tokens.append(
"Host groups: "
+ " ".join([el["name"] for el in difference_list])
+ " were created."
)
if len(intersection_list) > 0:
# determines difference between lists according to 'name' and 'title' pair
current_groups_dict = dict(
(el["name"], el["title"]) for el in current_groups
)
remainings_list = [
el
for el in intersection_list
if el.get("title") != current_groups_dict[el.get("name")]
]
if len(remainings_list) > 0:
update_host_groups(module, base_url, remainings_list, headers)
msg_tokens.append(
"Host groups: "
+ " ".join([el["name"] for el in remainings_list])
+ " were updated."
)
if len(msg_tokens) >= 1:
exit_changed(module, " ".join(msg_tokens))
else:
exit_ok(module, "Host groups already present.")
elif state == "absent":
# delete host groups that exist (intersection_list)
if len(intersection_list) > 0:
# extra check if title-s (alias-es) match.
delete_host_groups(module, base_url, intersection_list, headers)
exit_changed(
module,
"Host groups: "
+ " ".join([el["name"] for el in intersection_list])
+ " were deleted.",
)
else:
exit_failed(module, "Unknown error")
elif "name" in module.params and module.params.get("name", ""):
# Determine the current state of this particular host group
(
current_state,
current_title,
etag,
) = get_current_single_host_group(module, base_url, headers)
# Handle the host group accordingly to above findings and desired state
if state == "present" and current_state == "present":
headers["If-Match"] = etag
msg_tokens = []
if current_title != module.params["title"]:
update_single_host_group(module, base_url, headers)
msg_tokens.append("Host group was updated.")
if len(msg_tokens) >= 1:
exit_changed(module, " ".join(msg_tokens))
else:
exit_ok(module, "Host group already present.")
elif state == "present" and current_state == "absent":
create_single_host_group(module, base_url, headers)
exit_changed(module, "Host group created.")
elif state == "absent" and current_state == "absent":
exit_ok(module, "Host group already absent.")
elif state == "absent" and current_state == "present":
delete_single_host_group(module, base_url, headers)
exit_changed(module, "Host group deleted.")
else:
exit_failed(module, "Unknown error")
else:
exit_failed(module, "One should define either 'groups' or 'name'")
def main():
run_module()
if __name__ == "__main__":
main()