Debian Codegraph @

ansible_collections/f5networks/f5_modules/plugins/modules/bigip_device_syslog.py

raw symbols SCIP
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3 #
4 # Copyright: (c) 2018, F5 Networks Inc.
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 DOCUMENTATION = r'''
11 ---
12 module: bigip_device_syslog
13 short_description: Manage system-level syslog settings on BIG-IP
14 description:
15 - Manage system-level syslog settings on BIG-IP.
16 version_added: "1.0.0"
17 options:
18 auth_priv_from:
19 description:
20 - Specifies the lowest level of messages about user authentication
21 to include in the system log.
22 type: str
23 choices:
24 - alert
25 - crit
26 - debug
27 - emerg
28 - err
29 - info
30 - notice
31 - warning
32 auth_priv_to:
33 description:
34 - Specifies the highest level of messages about user authentication
35 to include in the system log.
36 type: str
37 choices:
38 - alert
39 - crit
40 - debug
41 - emerg
42 - err
43 - info
44 - notice
45 - warning
46 console_log:
47 description:
48 - Enables or disables logging emergency syslog messages to the
49 console.
50 type: bool
51 cron_from:
52 description:
53 - Specifies the lowest level of messages about time-based scheduling
54 to include in the system log.
55 type: str
56 choices:
57 - alert
58 - crit
59 - debug
60 - emerg
61 - err
62 - info
63 - notice
64 - warning
65 cron_to:
66 description:
67 - Specifies the highest level of messages about time-based
68 scheduling to include in the system log.
69 type: str
70 choices:
71 - alert
72 - crit
73 - debug
74 - emerg
75 - err
76 - info
77 - notice
78 - warning
79 daemon_from:
80 description:
81 - Specifies the lowest level of messages about daemon performance to
82 include in the system log.
83 type: str
84 choices:
85 - alert
86 - crit
87 - debug
88 - emerg
89 - err
90 - info
91 - notice
92 - warning
93 daemon_to:
94 description:
95 - Specifies the highest level of messages about daemon performance
96 to include in the system log.
97 type: str
98 choices:
99 - alert
100 - crit
101 - debug
102 - emerg
103 - err
104 - info
105 - notice
106 - warning
107 include:
108 description:
109 - Syslog-NG configuration to include in the device syslog config.
110 type: str
111 iso_date:
112 description:
113 - Enables or disables the ISO date format for messages in the log
114 files.
115 type: bool
116 kern_from:
117 description:
118 - Specifies the lowest level of kernel messages to include in the
119 system log.
120 type: str
121 choices:
122 - alert
123 - crit
124 - debug
125 - emerg
126 - err
127 - info
128 - notice
129 - warning
130 kern_to:
131 description:
132 - Specifies the highest level of kernel messages to include in the
133 system log.
134 type: str
135 choices:
136 - alert
137 - crit
138 - debug
139 - emerg
140 - err
141 - info
142 - notice
143 - warning
144 local6_from:
145 description:
146 - Specifies the lowest error level for messages from the local6
147 facility to include in the log.
148 type: str
149 choices:
150 - alert
151 - crit
152 - debug
153 - emerg
154 - err
155 - info
156 - notice
157 - warning
158 local6_to:
159 description:
160 - Specifies the highest error level for messages from the local6
161 facility to include in the log.
162 type: str
163 choices:
164 - alert
165 - crit
166 - debug
167 - emerg
168 - err
169 - info
170 - notice
171 - warning
172 mail_from:
173 description:
174 - Specifies the lowest level of mail log messages to include in the
175 system log.
176 type: str
177 choices:
178 - alert
179 - crit
180 - debug
181 - emerg
182 - err
183 - info
184 - notice
185 - warning
186 mail_to:
187 description:
188 - Specifies the highest level of mail log messages to include in the
189 system log.
190 type: str
191 choices:
192 - alert
193 - crit
194 - debug
195 - emerg
196 - err
197 - info
198 - notice
199 - warning
200 messages_from:
201 description:
202 - Specifies the lowest level of system messages to include in the
203 system log.
204 type: str
205 choices:
206 - alert
207 - crit
208 - debug
209 - emerg
210 - err
211 - info
212 - notice
213 - warning
214 messages_to:
215 description:
216 - Specifies the highest level of system messages to include in the
217 system log.
218 type: str
219 choices:
220 - alert
221 - crit
222 - debug
223 - emerg
224 - err
225 - info
226 - notice
227 - warning
228 user_log_from:
229 description:
230 - Specifies the lowest level of user account messages to include in
231 the system log.
232 type: str
233 choices:
234 - alert
235 - crit
236 - debug
237 - emerg
238 - err
239 - info
240 - notice
241 - warning
242 user_log_to:
243 description:
244 - Specifies the highest level of user account messages to include in
245 the system log.
246 type: str
247 choices:
248 - alert
249 - crit
250 - debug
251 - emerg
252 - err
253 - info
254 - notice
255 - warning
256 extends_documentation_fragment: f5networks.f5_modules.f5
257 author:
258 - Tim Rupp (@caphrim007)
259 '''
260
261 EXAMPLES = r'''
262 - name: Create a syslog config
263 bigip_device_syslog:
264 name: foo
265 provider:
266 password: secret
267 server: lb.mydomain.com
268 user: admin
269 delegate_to: localhost
270 '''
271
272 RETURN = r'''
273 auth_priv_from:
274 description: The new lowest user authentication logging level.
275 returned: changed
276 type: str
277 sample: alert
278 auth_priv_to:
279 description: The new highest user authentication logging level.
280 returned: changed
281 type: str
282 sample: emerg
283 console_log:
284 description: Whether logging to the console is enabled or not.
285 returned: changed
286 type: bool
287 sample: true
288 iso_date:
289 description: Whether ISO date format in logs is enabled or not.
290 returned: changed
291 type: bool
292 sample: false
293 cron_from:
294 description: The new lowest time-based scheduling logging level.
295 returned: changed
296 type: str
297 sample: emerg
298 cron_to:
299 description: The new highest time-based scheduling logging level.
300 returned: changed
301 type: str
302 sample: alert
303 daemon_from:
304 description: The new lowest daemon performance logging level.
305 returned: changed
306 type: str
307 sample: alert
308 daemon_to:
309 description: The new highest daemon performance logging level.
310 returned: changed
311 type: str
312 sample: alert
313 include:
314 description: The new extra syslog-ng configuration to include in syslog config.
315 returned: changed
316 type: str
317 sample: "filter f_remote_syslog { not (facility(local6)) };"
318 kern_from:
319 description: The new lowest kernel messages logging level.
320 returned: changed
321 type: str
322 sample: alert
323 kern_to:
324 description: The new highest kernel messages logging level.
325 returned: changed
326 type: str
327 sample: alert
328 local6_from:
329 description: The new lowest local6 facility logging level.
330 returned: changed
331 type: str
332 sample: alert
333 local6_to:
334 description: The new highest local6 facility logging level.
335 returned: changed
336 type: str
337 sample: alert
338 mail_from:
339 description: The new lowest mail log logging level.
340 returned: changed
341 type: str
342 sample: alert
343 mail_to:
344 description: The new highest mail log logging level.
345 returned: changed
346 type: str
347 sample: alert
348 messages_from:
349 description: The new lowest system logging level.
350 returned: changed
351 type: str
352 sample: alert
353 messages_to:
354 description: The new highest system logging level.
355 returned: changed
356 type: str
357 sample: alert
358 user_log_from:
359 description: The new lowest user account logging level.
360 returned: changed
361 type: str
362 sample: alert
363 user_log_to:
364 description: The new highest user account logging level.
365 returned: changed
366 type: str
367 sample: alert
368 '''
369 import re
370 from datetime import datetime
371 from ansible.module_utils.basic import AnsibleModule
372
373 from ..module_utils.bigip import F5RestClient
374 from ..module_utils.common import (
375 F5ModuleError, AnsibleF5Parameters, flatten_boolean, f5_argument_spec
376 )
377 from ..module_utils.compare import cmp_str_with_none
378 from ..module_utils.icontrol import tmos_version
379 from ..module_utils.teem import send_teem
380
381
382 class Parameters(AnsibleF5Parameters):
383 api_map = {
384 'authPrivFrom': 'auth_priv_from',
385 'authPrivTo': 'auth_priv_to',
386 'consoleLog': 'console_log',
387 'cronFrom': 'cron_from',
388 'cronTo': 'cron_to',
389 'daemonFrom': 'daemon_from',
390 'daemonTo': 'daemon_to',
391 'isoDate': 'iso_date',
392 'kernFrom': 'kern_from',
393 'kernTo': 'kern_to',
394 'local6From': 'local6_from',
395 'local6To': 'local6_to',
396 'mailFrom': 'mail_from',
397 'mailTo': 'mail_to',
398 'messagesFrom': 'messages_from',
399 'messagesTo': 'messages_to',
400 'userLogFrom': 'user_log_from',
401 'userLogTo': 'user_log_to',
402 }
403
404 api_attributes = [
405 'include',
406 'authPrivFrom',
407 'authPrivTo',
408 'consoleLog',
409 'cronFrom',
410 'cronTo',
411 'daemonFrom',
412 'daemonTo',
413 'isoDate',
414 'kernFrom',
415 'kernTo',
416 'local6From',
417 'local6To',
418 'mailFrom',
419 'mailTo',
420 'messagesFrom',
421 'messagesTo',
422 'userLogFrom',
423 'userLogTo',
424 ]
425
426 returnables = [
427 'include',
428 'auth_priv_from',
429 'auth_priv_to',
430 'console_log',
431 'cron_from',
432 'cron_to',
433 'daemon_from',
434 'daemon_to',
435 'iso_date',
436 'kern_from',
437 'kern_to',
438 'local6_from',
439 'local6_to',
440 'mail_from',
441 'mail_to',
442 'messages_from',
443 'messages_to',
444 'user_log_from',
445 'user_log_to',
446 ]
447
448 updatables = [
449 'include',
450 'auth_priv_from',
451 'auth_priv_to',
452 'console_log',
453 'cron_from',
454 'cron_to',
455 'daemon_from',
456 'daemon_to',
457 'iso_date',
458 'kern_from',
459 'kern_to',
460 'local6_from',
461 'local6_to',
462 'mail_from',
463 'mail_to',
464 'messages_from',
465 'messages_to',
466 'user_log_from',
467 'user_log_to',
468 ]
469
470 @property
471 def console_log(self):
472 return flatten_boolean(self._values['console_log'])
473
474 @property
475 def iso_date(self):
476 return flatten_boolean(self._values['iso_date'])
477
478
479 class ApiParameters(Parameters):
480 @property
481 def include(self):
482 if self._values['include'] in [None, 'none']:
483 return None
484 return self._values['include']
485
486
487 class ModuleParameters(Parameters):
488 @property
489 def include(self):
490 if self._values['include'] is None:
491 return None
492 if self._values['include'] in ['', 'none']:
493 return ''
494 unescaped_dquote = r'(?<!\\)"'
495 return re.sub(unescaped_dquote, "'", self._values['include'])
496
497
498 class Changes(Parameters):
499 def to_return(self):
500 result = {}
501 try:
502 for returnable in self.returnables:
503 result[returnable] = getattr(self, returnable)
504 result = self._filter_params(result)
505 except Exception:
506 raise
507 return result
508
509
510 class UsableChanges(Changes):
511 @property
512 def console_log(self):
513 if self._values['console_log'] is None:
514 return None
515 elif self._values['console_log'] == 'yes':
516 return 'enabled'
517 return 'disabled'
518
519 @property
520 def iso_date(self):
521 if self._values['iso_date'] is None:
522 return None
523 elif self._values['iso_date'] == 'yes':
524 return 'enabled'
525 return 'disabled'
526
527
528 class ReportableChanges(Changes):
529 @property
530 def console_log(self):
531 return flatten_boolean(self._values['console_log'])
532
533 @property
534 def iso_date(self):
535 return flatten_boolean(self._values['iso_date'])
536
537
538 class Difference(object):
539 def __init__(self, want, have=None):
540 self.want = want
541 self.have = have
542
543 def compare(self, param):
544 try:
545 result = getattr(self, param)
546 return result
547 except AttributeError:
548 return self.__default(param)
549
550 def __default(self, param):
551 attr1 = getattr(self.want, param)
552 try:
553 attr2 = getattr(self.have, param)
554 if attr1 != attr2:
555 return attr1
556 except AttributeError:
557 return attr1
558
559 @property
560 def include(self):
561 return cmp_str_with_none(self.want.include, self.have.include)
562
563
564 class ModuleManager(object):
565 def __init__(self, *args, **kwargs):
566 self.module = kwargs.get('module', None)
567 self.client = F5RestClient(**self.module.params)
568 self.want = ModuleParameters(params=self.module.params)
569 self.have = ApiParameters()
570 self.changes = UsableChanges()
571
572 def _set_changed_options(self):
573 changed = {}
574 for key in Parameters.returnables:
575 if getattr(self.want, key) is not None:
576 changed[key] = getattr(self.want, key)
577 if changed:
578 self.changes = UsableChanges(params=changed)
579
580 def _update_changed_options(self):
581 diff = Difference(self.want, self.have)
582 updatables = Parameters.updatables
583 changed = dict()
584 for k in updatables:
585 change = diff.compare(k)
586 if change is None:
587 continue
588 else:
589 if isinstance(change, dict):
590 changed.update(change)
591 else:
592 changed[k] = change
593 if changed:
594 self.changes = UsableChanges(params=changed)
595 return True
596 return False
597
598 def should_update(self):
599 result = self._update_changed_options()
600 if result:
601 return True
602 return False
603
604 def exec_module(self):
605 start = datetime.now().isoformat()
606 version = tmos_version(self.client)
607 result = dict()
608
609 changed = self.present()
610
611 reportable = ReportableChanges(params=self.changes.to_return())
612 changes = reportable.to_return()
613 result.update(**changes)
614 result.update(dict(changed=changed))
615 self._announce_deprecations(result)
616 send_teem(start, self.client, self.module, version)
617 return result
618
619 def _announce_deprecations(self, result):
620 warnings = result.pop('__warnings', [])
621 for warning in warnings:
622 self.client.module.deprecate(
623 msg=warning['msg'],
624 version=warning['version']
625 )
626
627 def present(self):
628 return self.update()
629
630 def update(self):
631 self.have = self.read_current_from_device()
632 if not self.should_update():
633 return False
634 if self.module.check_mode:
635 return True
636 self.update_on_device()
637 return True
638
639 def update_on_device(self):
640 params = self.changes.api_params()
641 uri = "https://{0}:{1}/mgmt/tm/sys/syslog".format(
642 self.client.provider['server'],
643 self.client.provider['server_port'],
644 )
645 resp = self.client.api.patch(uri, json=params)
646 try:
647 response = resp.json()
648 except ValueError as ex:
649 raise F5ModuleError(str(ex))
650
651 if resp.status in [200, 201] or 'code' in response and response['code'] in [200, 201]:
652 return True
653 raise F5ModuleError(resp.content)
654
655 def read_current_from_device(self):
656 uri = "https://{0}:{1}/mgmt/tm/sys/syslog".format(
657 self.client.provider['server'],
658 self.client.provider['server_port'],
659 )
660 resp = self.client.api.get(uri)
661 try:
662 response = resp.json()
663 except ValueError as ex:
664 raise F5ModuleError(str(ex))
665
666 if resp.status in [200, 201] or 'code' in response and response['code'] in [200, 201]:
667 return ApiParameters(params=response)
668 raise F5ModuleError(resp.content)
669
670
671 class ArgumentSpec(object):
672 def __init__(self):
673 self.supports_check_mode = True
674 levels = [
675 'alert', 'crit', 'debug', 'emerg', 'err', 'info', 'notice', 'warning'
676 ]
677
678 argument_spec = dict(
679 auth_priv_from=dict(choices=levels),
680 auth_priv_to=dict(choices=levels),
681 console_log=dict(type='bool'),
682 cron_from=dict(choices=levels),
683 cron_to=dict(choices=levels),
684 daemon_from=dict(choices=levels),
685 daemon_to=dict(choices=levels),
686 include=dict(),
687 iso_date=dict(type='bool'),
688 kern_from=dict(choices=levels),
689 kern_to=dict(choices=levels),
690 local6_from=dict(choices=levels),
691 local6_to=dict(choices=levels),
692 mail_from=dict(choices=levels),
693 mail_to=dict(choices=levels),
694 messages_from=dict(choices=levels),
695 messages_to=dict(choices=levels),
696 user_log_from=dict(choices=levels),
697 user_log_to=dict(choices=levels),
698 )
699 self.argument_spec = {}
700 self.argument_spec.update(f5_argument_spec)
701 self.argument_spec.update(argument_spec)
702
703
704 def main():
705 spec = ArgumentSpec()
706
707 module = AnsibleModule(
708 argument_spec=spec.argument_spec,
709 supports_check_mode=spec.supports_check_mode,
710 )
711
712 try:
713 mm = ModuleManager(module=module)
714 results = mm.exec_module()
715 module.exit_json(**results)
716 except F5ModuleError as ex:
717 module.fail_json(msg=str(ex))
718
719
720 if __name__ == '__main__':
721 main()