Debian Codegraph @

ansible_collections/community/zabbix/plugins/modules/zabbix_maintenance.py

raw
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3
4 # (c) 2013, Alexander Bulimov <[email protected]>
5 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
6
7 from __future__ import absolute_import, division, print_function
8 __metaclass__ = type
9
10
11 DOCUMENTATION = r"""
12 ---
13 module: zabbix_maintenance
14 short_description: Create Zabbix maintenance windows
15 description:
16 - This module will let you create Zabbix maintenance windows.
17 author: "Alexander Bulimov (@abulimov)"
18 requirements:
19 - "python >= 3.9"
20 options:
21 state:
22 description:
23 - Create or remove a maintenance window.
24 - Maintenance window to remove is identified by name.
25 default: present
26 choices: [ "present", "absent" ]
27 type: str
28 host_names:
29 description:
30 - Hosts to manage maintenance window for.
31 - B(Required) option when I(state=present) and I(host_groups) is not used.
32 aliases: [ "host_name" ]
33 type: list
34 elements: str
35 host_groups:
36 description:
37 - Host groups to manage maintenance window for.
38 - B(Required) option when I(state=present) and I(host_names) is not used.
39 aliases: [ "host_group" ]
40 type: list
41 elements: str
42 append:
43 description:
44 - Whether to append hosts and host groups to the existing maintenance.
45 type: bool
46 default: false
47 minutes:
48 description:
49 - Length of maintenance window in minutes.
50 - Will default to 10 minutes if not explicitly set
51 - This argument has been B(DEPRECATED) and replaced by the I(time_periods) argument and will be removed in 4.0.0
52 - B(Use of this argument only allows for the creation of a single one-time maintenance window.)
53 type: int
54 name:
55 description:
56 - Unique name of maintenance window.
57 required: true
58 type: str
59 desc:
60 description:
61 - Short description of maintenance window.
62 aliases: [ "description" ]
63 default: Created by Ansible
64 type: str
65 collect_data:
66 description:
67 - Type of maintenance. With data collection, or without.
68 type: bool
69 default: "yes"
70 visible_name:
71 description:
72 - Type of zabbix host name to use for identifying hosts to include in the maintenance.
73 - I(visible_name=yes) to search by visible name, I(visible_name=no) to search by technical name.
74 type: bool
75 default: "yes"
76 active_since:
77 description:
78 - Time when the maintenance becomes active.
79 - The given value will be rounded down to minutes.
80 - Uses `datetime.datetime.now() if not specified.
81 - NOTE - This time will not update across multiple runs unless explicitly set.
82 type: "str"
83 default: ""
84 active_till:
85 description:
86 - Time when the maintenance stops being active.
87 - The given value will be rounded down to minutes.
88 - Gets calculated from I(minutes) if not specified when using I(minutes) only.
89 - When using I(time_periods) defaults to one year from I(active_since)
90 type: "str"
91 default: ""
92 tags:
93 description:
94 - List of tags to assign to the hosts in maintenance.
95 - Requires I(collect_data=yes).
96 type: list
97 elements: dict
98 suboptions:
99 tag:
100 description:
101 - Name of the tag.
102 type: str
103 required: true
104 value:
105 description:
106 - Value of the tag.
107 type: str
108 default: ""
109 operator:
110 description:
111 - Condition operator.
112 - Possible values is
113 - 0 - Equals
114 - 2 - Contains
115 type: int
116 default: 2
117 time_periods:
118 description:
119 - List scheduled outages within the maintenance period.
120 - This argument replaces the I(minutes) argument.
121 aliases: [ "time_period" ]
122 type: list
123 elements: dict
124 suboptions:
125 frequency:
126 description:
127 - The frequency that this maintenance window will occur.
128 type: str
129 required: true
130 choices: ['once', 'daily', 'weekly', 'monthly']
131 duration:
132 description:
133 - The duration of this maintenance window in minutes.
134 type: int
135 default: 10
136 start_date:
137 description:
138 - The date that the outage will occur on.
139 - for a I(frequency) of I(once) only.
140 - Uses `datetime.date.today() if not specified.
141 type: str
142 start_time:
143 description:
144 - The time that this outage will start on.
145 - Times should be entered in the HH:MM format using a 24-hour clock
146 type: str
147 required: true
148 every:
149 description:
150 - The interval between each event.
151 - For a I(frequency) of I(daily) or I(weekly) this must be an B(integer).
152 - For example when I(frequency=daily) and I(every=2) the outage would occur every other day.
153 - For I'(frequency=monthly) with I(day_of_week) set, valid options include I(first), I(second), I(third), I(forth), I(last) (week)
154 type: str
155 day_of_week:
156 description:
157 - The day of the week the maintenance window will occur.
158 - This argument is B(required) if I(frequency=weekly).
159 - This argument is B(required) if I(frequency=monthly) when I(day_of_month) is not set.
160 type: list
161 elements: str
162 day_of_month:
163 description:
164 - The day of the month the maintenance window will occur.
165 - This argument is B(required) if I(frequency=monthly) when I(day_of_week) is not set.
166 type: int
167 months:
168 description:
169 - The months that the maintenance window will occur.
170 - This argument is B(required) when the I(frequency=monthly)
171 aliases: [ "month" ]
172 type: list
173 elements: str
174
175 extends_documentation_fragment:
176 - community.zabbix.zabbix
177
178
179 notes:
180 - Useful for setting hosts in maintenance mode before big update,
181 and removing maintenance window after update.
182 - Module creates maintenance window from now() to now() + minutes,
183 so if Zabbix server's time and host's time are not synchronized,
184 you will get strange results.
185 """
186
187 EXAMPLES = r"""
188 # If you want to use Username and Password to be authenticated by Zabbix Server
189 - name: Set credentials to access Zabbix Server API
190 ansible.builtin.set_fact:
191 ansible_user: Admin
192 ansible_httpapi_pass: zabbix
193
194 # If you want to use API token to be authenticated by Zabbix Server
195 # https://www.zabbix.com/documentation/current/en/manual/web_interface/frontend_sections/administration/general#api-tokens
196 - name: Set API token
197 ansible.builtin.set_fact:
198 ansible_zabbix_auth_key: 8ec0d52432c15c91fcafe9888500cf9a607f44091ab554dbee860f6b44fac895
199
200 - name: Create a named maintenance window for host www1 for 90 minutes
201 # set task level variables as we change ansible_connection plugin here
202 vars:
203 ansible_network_os: community.zabbix.zabbix
204 ansible_connection: httpapi
205 ansible_httpapi_port: 443
206 ansible_httpapi_use_ssl: true
207 ansible_httpapi_validate_certs: false
208 ansible_zabbix_url_path: "zabbixeu" # If Zabbix WebUI runs on non-default (zabbix) path ,e.g. http://<FQDN>/zabbixeu
209 ansible_host: zabbix-example-fqdn.org
210 community.zabbix.zabbix_maintenance:
211 name: Update of www1
212 host_name: www1.example.com
213 state: present
214 time_periods:
215 - frequency: once
216 duration: 90
217 start_date: 2025-01-01
218 start_time: 17:00
219
220 - name: Create a maintenance window that occurs every other day for host www1 and host groups Office and Dev
221 # set task level variables as we change ansible_connection plugin here
222 vars:
223 ansible_network_os: community.zabbix.zabbix
224 ansible_connection: httpapi
225 ansible_httpapi_port: 443
226 ansible_httpapi_use_ssl: true
227 ansible_httpapi_validate_certs: false
228 ansible_zabbix_url_path: "zabbixeu" # If Zabbix WebUI runs on non-default (zabbix) path ,e.g. http://<FQDN>/zabbixeu
229 ansible_host: zabbix-example-fqdn.org
230 community.zabbix.zabbix_maintenance:
231 name: Update of www1
232 host_name: www1.example.com
233 host_groups:
234 - Office
235 - Dev
236 state: present
237 tags:
238 - tag: ExampleHostsTag
239 - tag: ExampleHostsTag2
240 value: ExampleTagValue
241 - tag: ExampleHostsTag3
242 value: ExampleTagValue
243 operator: 0
244 time_periods:
245 - frequency: daily
246 start_time: 17:00
247 every: 2
248
249 - name: Create a monthly (on the second Monday of the month) maintenance window for hosts www1 and db1, without data collection.
250 # set task level variables as we change ansible_connection plugin here
251 vars:
252 ansible_network_os: community.zabbix.zabbix
253 ansible_connection: httpapi
254 ansible_httpapi_port: 443
255 ansible_httpapi_use_ssl: true
256 ansible_httpapi_validate_certs: false
257 ansible_zabbix_url_path: "zabbixeu" # If Zabbix WebUI runs on non-default (zabbix) path ,e.g. http://<FQDN>/zabbixeu
258 ansible_host: zabbix-example-fqdn.org
259 community.zabbix.zabbix_maintenance:
260 name: update
261 host_names:
262 - www1.example.com
263 - db1.example.com
264 state: present
265 collect_data: false
266 time_periods:
267 - frequency: monthly
268 start_time: 17:00
269 day_of_week: Monday
270 every: second
271
272 - name: Remove maintenance window by name
273 # set task level variables as we change ansible_connection plugin here
274 vars:
275 ansible_network_os: community.zabbix.zabbix
276 ansible_connection: httpapi
277 ansible_httpapi_port: 443
278 ansible_httpapi_use_ssl: true
279 ansible_httpapi_validate_certs: false
280 ansible_zabbix_url_path: "zabbixeu" # If Zabbix WebUI runs on non-default (zabbix) path ,e.g. http://<FQDN>/zabbixeu
281 ansible_host: zabbix-example-fqdn.org
282 community.zabbix.zabbix_maintenance:
283 name: Test1
284 state: absent
285
286 - name: Create maintenance window by date. Window will occur on the 1st of January, April, July, and October
287 # set task level variables as we change ansible_connection plugin here
288 vars:
289 ansible_network_os: community.zabbix.zabbix
290 ansible_connection: httpapi
291 ansible_httpapi_port: 443
292 ansible_httpapi_use_ssl: true
293 ansible_httpapi_validate_certs: false
294 ansible_zabbix_url_path: "zabbixeu" # If Zabbix WebUI runs on non-default (zabbix) path ,e.g. http://<FQDN>/zabbixeu
295 ansible_host: zabbix-example-fqdn.org
296 community.zabbix.zabbix_maintenance:
297 name: TestDate
298 state: present
299 host_names:
300 - host.example.org
301 active_since: "1979-09-19 09:00"
302 active_till: "1979-09-19 17:00"
303 time_periods:
304 - frequency: monthly
305 months:
306 - January
307 - April
308 - July
309 - October
310 day_of_month: 1
311 start_time: 17:00
312 """
313
314 import datetime
315 import time
316
317 from ansible.module_utils.basic import AnsibleModule
318 from ansible_collections.community.zabbix.plugins.module_utils.base import ZabbixBase
319 import ansible_collections.community.zabbix.plugins.module_utils.helpers as zabbix_utils
320 from ansible.module_utils.compat.version import LooseVersion
321
322
323 class MaintenanceModule(ZabbixBase):
324 def create_maintenance(self, group_ids, host_ids, start_time, end_time,
325 maintenance_type, time_periods, name, desc, tags):
326 parameters = {
327 "groups": [{"groupid": groupid} for groupid in group_ids],
328 "hosts": [{"hostid": hostid} for hostid in host_ids],
329 "name": name,
330 "maintenance_type": maintenance_type,
331 "active_since": str(start_time),
332 "active_till": str(end_time),
333 "description": desc,
334 "timeperiods": time_periods
335 }
336 if LooseVersion(self._zbx_api_version) < LooseVersion("7.0"):
337 parameters["groupids"] = group_ids
338 parameters["hostids"] = host_ids
339 del parameters["groups"]
340 del parameters["hosts"]
341 if tags is not None:
342 parameters["tags"] = tags
343 self._zapi.maintenance.create(parameters)
344 return 0, None, None
345
346 def update_maintenance(self, maintenance_id, group_ids, host_ids,
347 start_time, end_time, maintenance_type, time_periods, desc, tags):
348 parameters = {
349 "maintenanceid": maintenance_id,
350 "groups": [{"groupid": groupid} for groupid in group_ids],
351 "hosts": [{"hostid": hostid} for hostid in host_ids],
352 "maintenance_type": maintenance_type,
353 "active_since": str(start_time),
354 "active_till": str(end_time),
355 "description": desc,
356 "timeperiods": time_periods
357 }
358 if LooseVersion(self._zbx_api_version) < LooseVersion("7.0"):
359 parameters["groupids"] = group_ids
360 parameters["hostids"] = host_ids
361 del parameters["groups"]
362 del parameters["hosts"]
363 if tags is not None:
364 parameters["tags"] = tags
365 self._zapi.maintenance.update(parameters)
366 return 0, None, None
367
368 def get_maintenance(self, name):
369 parameters = {
370 "filter": {"name": name},
371 "output": "extend",
372 "selectHostGroups": "extend",
373 "selectHosts": "extend",
374 "selectTags": "extend",
375 "selectTimeperiods": "extend"
376 }
377 if LooseVersion(self._zbx_api_version) < LooseVersion("7.0"):
378 parameters["selectGroups"] = parameters["selectHostGroups"]
379 del parameters["selectHostGroups"]
380 maintenances = self._zapi.maintenance.get(parameters)
381
382 for maintenance in maintenances:
383 groupids = []
384 if "hostgroups" in maintenance:
385 groups = maintenance["hostgroups"]
386 maintenance.pop("hostgroups")
387 elif "groups" in maintenance:
388 groups = maintenance["groups"]
389
390 if groups:
391 for group in groups:
392 groupids.append(group["groupid"])
393 maintenance["groups"] = groupids
394
395 if "hosts" in maintenance:
396 hostids = []
397 for host in maintenance["hosts"]:
398 hostids.append(host["hostid"])
399 maintenance["hosts"] = hostids
400
401 timeperiods = []
402 for period in maintenance["timeperiods"]:
403 if period["timeperiod_type"] in ["0", "2"]:
404 for f in ["day", "dayofweek", "month"]:
405 if f in period.keys():
406 period.pop(f)
407 if period["timeperiod_type"] == "0" and "every" in period.keys():
408 period.pop("every")
409 timeperiods.append(period)
410 maintenance["timeperiods"] = timeperiods
411 return 0, maintenance, None
412 return 0, None, None
413
414 def delete_maintenance(self, maintenance_id):
415 self._zapi.maintenance.delete([maintenance_id])
416 return 0, None, None
417
418 def get_group_ids(self, host_groups):
419 group_ids = []
420 for group in host_groups:
421 result = self._zapi.hostgroup.get(
422 {
423 "output": "extend",
424 "filter":
425 {
426 "name": group
427 }
428 }
429 )
430
431 if not result:
432 return 1, None, "Group id for group %s not found" % group
433
434 group_ids.append(result[0]["groupid"])
435
436 return 0, group_ids, None
437
438 def get_host_ids(self, host_names, zabbix_host):
439 host_ids = []
440 for host in host_names:
441 result = self._zapi.host.get(
442 {
443 "output": "extend",
444 "filter":
445 {
446 zabbix_host: host
447 }
448 }
449 )
450
451 if not result:
452 return 1, None, "Host id for host %s not found" % host
453
454 host_ids.append(result[0]["hostid"])
455
456 return 0, host_ids, None
457
458 def check_maint_properties(self, maintenance, groups, hosts, start_time,
459 end_time, maintenance_type, time_periods, desc, tags):
460 if sorted(groups) != sorted(maintenance["groups"]):
461 return True
462 if sorted(hosts) != sorted(maintenance["hosts"]):
463 return True
464 if str(int(start_time)) != maintenance["active_since"]:
465 return True
466 if str(int(end_time)) != maintenance["active_till"]:
467 return True
468 if str(desc) != maintenance["description"]:
469 return True
470 if str(maintenance_type) != maintenance["maintenance_type"]:
471 return True
472 if tags is not None and "tags" in maintenance:
473 s1 = sorted(tags, key=lambda k: (k["tag"], k.get("value", "")))
474 s2 = sorted(maintenance["tags"], key=lambda k: (k["tag"], k.get("value", "")))
475 if s1 != s2:
476 for item in s1:
477 comp = s2.pop(0)
478 if sorted(item.keys()) != sorted(comp.keys()):
479 return True
480 for k in item.keys():
481 if str(item[k]) != str(comp[k]):
482 return True
483
484 if len(zabbix_utils.helper_compare_lists(time_periods, maintenance["timeperiods"], [])) > 0:
485 return True
486
487
488 def parse_days_of_week(module, days_of_week):
489 DAYS = {
490 "Monday": 1,
491 "Tuesday": 2,
492 "Wednesday": 4,
493 "Thursday": 8,
494 "Friday": 16,
495 "Saturday": 32,
496 "Sunday": 64
497 }
498
499 if len(days_of_week) < 1:
500 module.fail_json(msg="The 'days_of_week' argument must be set.")
501
502 total = 0
503
504 try:
505 for day in days_of_week:
506 total += DAYS[day]
507 except KeyError:
508 module.fail_json(msg=f"{day} is not a valid value for the The 'days_of_week' argument.")
509 return total
510
511
512 def parse_week_of_month(module, every):
513 EVERY = {
514 "first": 1,
515 "second": 2,
516 "third": 3,
517 "fourth": 4
518 }
519
520 if every in EVERY.keys():
521 return EVERY[every]
522 else:
523 module.fail_json(msg="The value in 'every' is not valid")
524
525
526 def parse_months(module, months):
527 MONTHS = {
528 "January": 1,
529 "February": 2,
530 "March": 4,
531 "April": 8,
532 "May": 16,
533 "June": 32,
534 "July": 64,
535 "August": 128,
536 "September": 256,
537 "October": 512,
538 "November": 1024,
539 "December": 2048
540 }
541
542 if months is None:
543 return 4095
544 elif len(months) < 1:
545 module.fail_json(msg="The 'months' argument may not be an empty list.")
546
547 total = 0
548
549 try:
550 for month in months:
551 total += MONTHS[month]
552 except KeyError:
553 module.fail_json(msg=f"{month} is not a valid value for the the 'month' argument.")
554 return total
555
556
557 def parse_periods(module, time_periods, start_date):
558 PERIODS = {
559 "once": 0,
560 "daily": 2,
561 "weekly": 3,
562 "monthly": 4
563 }
564 items = []
565
566 for period in time_periods:
567 this_period = {}
568 frequeny = period['frequency']
569 duration = period['duration'] * 60
570 start_date = period['start_date']
571 start_time = period['start_time']
572 every = period['every']
573 day_of_week = period['day_of_week']
574 day_of_month = period['day_of_month']
575 months = period['months']
576
577 NULL_FIELDS = {
578 "once": {
579 "day_of_month": day_of_month,
580 "day_of_week": day_of_week,
581 "months": months,
582 "every": every
583 },
584 "daily": {
585 "day_of_month": day_of_month,
586 "day_of_week": day_of_week,
587 "months": months,
588 "start_date": start_date
589 },
590 "weekly": {
591 "day_of_month": day_of_month,
592 "months": months,
593 "start_date": start_date
594 },
595 "monthly": {"start_date": start_date}
596 }
597
598 # Sanitize fields
599 null_fields = NULL_FIELDS[frequeny]
600 for f in null_fields.keys():
601 if null_fields[f]:
602 module.fail_json(msg=f"The field '{f}' may not be set for a '{frequeny}' of 'once'")
603
604 # Parse start_date/time fields
605 if frequeny == "once":
606 start_date = start_date + " " + start_time
607 start_date = datetime.datetime.fromisoformat(start_date)
608 start_date = int(time.mktime(start_date.timetuple()))
609 start_date = (start_date // 60) * 60
610 this_period['start_date'] = str(start_date)
611 else:
612 start_time = datetime.time.fromisoformat(start_time)
613 start_time = ((start_time.hour * 60) + start_time.minute) * 60
614 this_period['start_time'] = str(start_time)
615
616 # Parse Every and Day of Week
617 if frequeny in ["daily", "weekly"]:
618 try:
619 every = int(every)
620 except ValueError:
621 module.fail_json(msg=f"The value '{every}' is not valid for the 'every' argument.")
622 if every >= 1:
623 this_period['every'] = str(every)
624 else:
625 module.fail_json(msg="The 'every' argument must be a posative number.")
626
627 if frequeny == "weekly":
628 day_of_week = parse_days_of_week(module, day_of_week)
629 this_period["dayofweek"] = str(day_of_week)
630 elif frequeny == "monthly":
631 if day_of_month and day_of_week:
632 module.fail_json(msg="The 'day_of_week' argument may not be used with the 'day_of_month' argument.")
633
634 if day_of_week:
635 day_of_week = parse_days_of_week(module, day_of_week)
636 this_period['dayofweek'] = str(day_of_week)
637 this_period['every'] = str(parse_week_of_month(module, every))
638 else:
639 if not 1 <= day_of_month <= 31:
640 module.fail_json(msg=f"The value '{str(day_of_month)}' in the 'day_of_month' argument is not valid.")
641 else:
642 this_period['day'] = str(day_of_month)
643
644 this_period["month"] = str(parse_months(module, months))
645
646 this_period["timeperiod_type"] = str(PERIODS[frequeny])
647 this_period["period"] = str(duration)
648 items.append(this_period)
649 return items
650
651
652 def main():
653 argument_spec = zabbix_utils.zabbix_common_argument_spec()
654 argument_spec.update(
655 dict(
656 state=dict(
657 type="str",
658 required=False,
659 default="present",
660 choices=["present", "absent"]),
661 host_names=dict(
662 type="list",
663 required=False,
664 default=None,
665 aliases=["host_name"],
666 elements="str"),
667 minutes=dict(
668 type="int",
669 required=False),
670 host_groups=dict(
671 type="list",
672 required=False,
673 default=None,
674 aliases=["host_group"],
675 elements="str"),
676 append=dict(type="bool", required=False, default=False),
677 name=dict(type="str", required=True),
678 desc=dict(type="str", required=False, default="Created by Ansible", aliases=["description"]),
679 collect_data=dict(type="bool", required=False, default=True),
680 visible_name=dict(type="bool", required=False, default=True),
681 active_since=dict(type="str", required=False, default=""),
682 active_till=dict(type="str", required=False, default=""),
683 tags=dict(
684 type="list",
685 elements="dict",
686 required=False,
687 options=dict(
688 tag=dict(type="str", required=True),
689 operator=dict(type="int", default=2),
690 value=dict(type="str", default="")
691 )
692 ),
693 time_periods=dict(
694 type="list",
695 elements="dict",
696 required=False,
697 aliases=['time_period'],
698 options=dict(
699 frequency=dict(
700 type="str",
701 required=True,
702 choices=['once', 'daily', 'weekly', 'monthly']
703 ),
704 duration=dict(type="int", default=10),
705 start_date=dict(type="str"),
706 start_time=dict(type="str", required=True),
707 every=dict(type="str"),
708 day_of_week=dict(type="list", elements="str"),
709 day_of_month=dict(type="int"),
710 months=dict(type="list", elements="str", aliases=["month"])
711 )
712 )
713 )
714 )
715 mutually_exclusive = [("minutes", "time_periods")]
716
717 module = AnsibleModule(
718 argument_spec=argument_spec,
719 mutually_exclusive=mutually_exclusive,
720 supports_check_mode=True
721 )
722
723 maint = MaintenanceModule(module)
724 host_names = module.params["host_names"]
725 host_groups = module.params["host_groups"]
726 append = module.params["append"]
727 state = module.params["state"]
728 minutes = module.params["minutes"]
729 name = module.params["name"]
730 desc = module.params["desc"]
731 collect_data = module.params["collect_data"]
732 visible_name = module.params["visible_name"]
733 active_since = module.params["active_since"]
734 active_till = module.params["active_till"]
735 tags = module.params["tags"]
736 time_periods = module.params["time_periods"]
737
738 # Set Default for minutes if needed
739 if not time_periods:
740 minutes = minutes if minutes else 10
741 module.params["minutes"] = minutes
742
743 if collect_data:
744 maintenance_type = 0
745 else:
746 maintenance_type = 1
747 if tags is not None:
748 module.fail_json(msg="Tags cannot be provided for maintenance without data collection.")
749
750 if visible_name:
751 zabbix_host = "name"
752 else:
753 zabbix_host = "host"
754
755 changed = False
756
757 if state == "present":
758 if not host_names and not host_groups:
759 module.fail_json(
760 msg="At least one host_name or host_group must be defined for each created maintenance.")
761
762 if host_groups:
763 (rc, group_ids, error) = maint.get_group_ids(host_groups)
764 if rc != 0:
765 module.fail_json(msg="Failed to get group_ids: %s" % error)
766 else:
767 group_ids = []
768
769 if host_names:
770 (rc, host_ids, error) = maint.get_host_ids(host_names, zabbix_host)
771 if rc != 0:
772 module.fail_json(msg="Failed to get host_ids: %s" % error)
773 else:
774 host_ids = []
775
776 (rc, maintenance, error) = maint.get_maintenance(name)
777 if rc != 0:
778 module.fail_json(
779 msg="Failed to check maintenance %s existence: %s" % (name, error))
780
781 if maintenance:
782 if active_since == "":
783 start_time = maintenance['active_since']
784 else:
785 start_time = datetime.datetime.fromisoformat(active_since)
786 start_time = int(time.mktime(start_time.timetuple()))
787
788 if active_till == "":
789 if minutes:
790 end_time = int(start_time) + (minutes * 60)
791 else:
792 end_time = maintenance['active_till']
793 else:
794 end_time = datetime.datetime.fromisoformat(active_till)
795 end_time = int(time.mktime(end_time.timetuple()))
796 else:
797 start_time = datetime.datetime.fromisoformat(active_since) if active_since != "" else datetime.datetime.now().replace(second=0)
798 start_time = int(time.mktime(start_time.timetuple()))
799
800 # Set End Time
801 if active_till:
802 end_time = datetime.datetime.fromisoformat(active_till)
803 end_time = int(time.mktime(end_time.timetuple()))
804 elif minutes:
805 end_time = start_time + (minutes * 60)
806 else:
807 end_time = start_time + (60 * 60 * 24 * 365)
808
809 # Logic for backwards compatability. Remove with 4.0.0
810 if minutes:
811 if time_periods:
812 module.fail_json(msg="The 'time_periods' artibute cannot be set with the 'minutes' attribute.")
813 time_periods = [{
814 "timeperiod_type": "0",
815 "start_date": str(start_time),
816 "period": str((minutes * 60))
817 }]
818 else:
819 time_periods = parse_periods(module, time_periods, active_since)
820
821 if maintenance:
822 if append:
823 group_ids = list(set(group_ids + maintenance["groups"]))
824 host_ids = list(set(host_ids + maintenance["hosts"]))
825
826 if maint.check_maint_properties(maintenance, group_ids, host_ids, start_time, end_time, maintenance_type, time_periods, desc, tags):
827 if module.check_mode:
828 changed = True
829 else:
830 (rc, data, error) = maint.update_maintenance(
831 maintenance["maintenanceid"], group_ids, host_ids, start_time, end_time, maintenance_type, time_periods, desc, tags)
832 if rc == 0:
833 changed = True
834 else:
835 module.fail_json(
836 msg="Failed to update maintenance: %s" % error)
837 else:
838 if module.check_mode:
839 changed = True
840 else:
841 (rc, data, error) = maint.create_maintenance(
842 group_ids, host_ids, start_time, end_time, maintenance_type, time_periods, name, desc, tags)
843 if rc == 0:
844 changed = True
845 else:
846 module.fail_json(
847 msg="Failed to create maintenance: %s" % error)
848 # Absent
849 else:
850 (rc, maintenance, error) = maint.get_maintenance(name)
851 if rc != 0:
852 module.fail_json(
853 msg="Failed to check maintenance %s existence: %s" % (name, error))
854
855 if maintenance:
856 if module.check_mode:
857 changed = True
858 else:
859 (rc, data, error) = maint.delete_maintenance(
860 maintenance["maintenanceid"])
861 if rc == 0:
862 changed = True
863 else:
864 module.fail_json(
865 msg="Failed to remove maintenance: %s" % error)
866
867 module.exit_json(changed=changed)
868
869
870 if __name__ == "__main__":
871 main()