Debian Codegraph @

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

raw symbols SCIP
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3 #
4 # Copyright: (c) 2017, 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_snmp_trap
13 short_description: Manipulate SNMP trap information on a BIG-IP
14 description:
15 - Manipulate SNMP trap information on a BIG-IP system.
16 version_added: "1.0.0"
17 options:
18 name:
19 description:
20 - Name of the SNMP configuration endpoint.
21 type: str
22 required: True
23 snmp_version:
24 description:
25 - Specifies to which Simple Network Management Protocol (SNMP) version
26 the trap destination applies.
27 type: str
28 choices:
29 - '1'
30 - '2c'
31 - '3'
32 community:
33 description:
34 - Specifies the community name for the trap destination.
35 type: str
36 destination:
37 description:
38 - Specifies the address for the trap destination. This can be either an
39 IP address or a hostname.
40 type: str
41 port:
42 description:
43 - Specifies the port for the trap destination.
44 type: str
45 network:
46 description:
47 - Specifies the name of the trap network. This option is not supported in
48 versions of BIG-IP prior to 12.1.0, and is simply ignored on those versions.
49 - The value C(default) was removed in BIG-IP version 13.1.0. Specifying this
50 value when configuring a BIG-IP causes the module to stop and report
51 an error. In this case, choose one of the other options, such as
52 C(management).
53 type: str
54 choices:
55 - other
56 - management
57 - default
58 security_name:
59 description:
60 - Specifies the security name to used for v3 snmp trap
61 - Required for the C(snmp_version) matches C(v3).
62 type: str
63 version_added: "1.16.0"
64 security_level:
65 description:
66 - Specifies the port for the trap destination.
67 - Required for the C(snmp_version) matches C(v3).
68 type: str
69 choices:
70 - auth-no-privacy
71 - auth-privacy
72 version_added: "1.16.0"
73 auth_protocol:
74 description:
75 - Specifies the Authentication protocol to be used for snmp v3 traps
76 - Required for the C(security_level)
77 type: str
78 choices:
79 - sha
80 - md5
81 version_added: "1.16.0"
82 auth_password:
83 description:
84 - Specifies the Authentication protocol password to be used for snmp v3 traps
85 - Required for the C(snmp_version) matches C(v3) and for the C(security_level)
86 type: str
87 version_added: "1.16.0"
88 privacy_protocol:
89 description:
90 - Specifies the Privacy protocol to be used for snmp v3 traps
91 - Required for the C(security_level) matches c(auth-privacy)
92 type: str
93 choices:
94 - aes
95 - des
96 version_added: "1.16.0"
97 privacy_password:
98 description:
99 - Specifies the Privacy protocol password to be used for snmp v3 traps
100 - Required for the C(security_level) matches c(auth-privacy)
101 type: str
102 version_added: "1.16.0"
103 state:
104 description:
105 - When C(present), ensures the resource exists.
106 - When C(absent), ensures the resource does not exist.
107 type: str
108 choices:
109 - present
110 - absent
111 default: present
112 partition:
113 description:
114 - Device partition to manage resources on.
115 type: str
116 default: Common
117 notes:
118 - This module only supports version v1 and v2c of SNMP.
119 - The C(network) option is not supported on versions of BIG-IP prior to 12.1.0 because
120 the platform did not support that option until 12.1.0. If used on versions
121 prior to 12.1.0, it is simply be ignored.
122 extends_documentation_fragment: f5networks.f5_modules.f5
123 author:
124 - Tim Rupp (@caphrim007)
125 - Wojciech Wypior (@wojtek0806)
126 '''
127
128 EXAMPLES = r'''
129 - name: Create snmp v1 trap
130 bigip_snmp_trap:
131 community: general
132 destination: 1.2.3.4
133 name: my-trap1
134 network: management
135 port: 9000
136 snmp_version: 1
137 provider:
138 server: lb.mydomain.com
139 user: admin
140 password: secret
141 delegate_to: localhost
142
143 - name: Create snmp v2 trap
144 bigip_snmp_trap:
145 community: general
146 destination: 5.6.7.8
147 name: my-trap2
148 network: default
149 port: 7000
150 snmp_version: 2c
151 provider:
152 server: lb.mydomain.com
153 user: admin
154 password: secret
155 delegate_to: localhost
156
157 - name: Create snmp v3 trap
158 bigip_snmp_trap:
159 community: general
160 destination: 5.6.7.9
161 name: my-trap3
162 network: management
163 port: 7001
164 snmp_version: 3
165 auth_protocol: 'sha'
166 auth_password: 'test12345'
167 security_name: "testsec2"
168 security_level: "auth-no-privacy"
169 provider:
170 server: lb.mydomain.com
171 user: admin
172 password: secret
173 state: absent
174 delegate_to: localhost
175
176 - name: Create snmp v3 trap-2
177 bigip_snmp_trap:
178 community: general
179 destination: 5.6.7.10
180 name: my-trap4
181 network: management
182 port: 7002
183 snmp_version: 3
184 auth_protocol: 'sha'
185 auth_password: 'test123456'
186 security_name: "testsec3"
187 security_level: "auth-privacy"
188 privacy_protocol: "des"
189 privacy_password: 'test@12345'
190 provider:
191 server: lb.mydomain.com
192 user: admin
193 password: secret
194 state: absent
195 delegate_to: localhost
196 '''
197
198 RETURN = r'''
199 snmp_version:
200 description: The new C(snmp_version) configured on the remote device.
201 returned: changed and success
202 type: str
203 sample: 2c
204 community:
205 description: The new C(community) name for the trap destination.
206 returned: changed and success
207 type: list
208 sample: secret
209 destination:
210 description: The new address for the trap destination in either IP or hostname form.
211 returned: changed and success
212 type: str
213 sample: 1.2.3.4
214 port:
215 description: The new C(port) of the trap destination.
216 returned: changed and success
217 type: str
218 sample: 900
219 network:
220 description: The new name of the network the SNMP trap is on.
221 returned: changed and success
222 type: str
223 sample: management
224 '''
225 import traceback
226 from datetime import datetime
227
228 try:
229 from packaging.version import Version
230 except ImportError:
231 HAS_PACKAGING = False
232 Version = None
233 PACKAGING_IMPORT_ERROR = traceback.format_exc()
234 else:
235 HAS_PACKAGING = True
236 PACKAGING_IMPORT_ERROR = None
237
238 from ansible.module_utils.basic import (
239 AnsibleModule, missing_required_lib, env_fallback
240 )
241
242 from ..module_utils.bigip import F5RestClient
243 from ..module_utils.common import (
244 F5ModuleError, AnsibleF5Parameters, transform_name, f5_argument_spec
245 )
246 from ..module_utils.icontrol import tmos_version
247 from ..module_utils.teem import send_teem
248
249
250 class Parameters(AnsibleF5Parameters):
251 api_map = {
252 'version': 'snmp_version',
253 'community': 'community',
254 'host': 'destination',
255 'securityName': 'security_name',
256 'authProtocol': 'auth_protocol',
257 'authPassword': 'auth_password',
258 'securityLevel': 'security_level',
259 'privacyProtocol': 'privacy_protocol',
260 'privacyPassword': 'privacy_password',
261 }
262
263 @property
264 def snmp_version(self):
265 if self._values['snmp_version'] is None:
266 return None
267 return str(self._values['snmp_version'])
268
269 @property
270 def port(self):
271 if self._values['port'] is None:
272 return None
273 return int(self._values['port'])
274
275 def to_return(self):
276 result = {}
277 for returnable in self.returnables:
278 result[returnable] = getattr(self, returnable)
279 result = self._filter_params(result)
280 return result
281
282
283 class V3Parameters(Parameters):
284 updatables = [
285 'snmp_version',
286 'community',
287 'destination',
288 'port',
289 'network',
290 'security_name',
291 'auth_protocol',
292 'security_level',
293 'privacy_protocol',
294 ]
295
296 returnables = [
297 'snmp_version',
298 'community',
299 'destination',
300 'port',
301 'network',
302 'security_name',
303 'auth_protocol',
304 'auth_password',
305 'security_level',
306 'privacy_protocol',
307 'privacy_password',
308 ]
309
310 api_attributes = [
311 'version',
312 'community',
313 'host',
314 'port',
315 'network',
316 'securityName',
317 'authProtocol',
318 'authPassword',
319 'securityLevel',
320 'privacyProtocol',
321 'privacyPassword',
322 ]
323
324 @property
325 def network(self):
326 if self._values['network'] is None:
327 return None
328 network = str(self._values['network'])
329 if network == 'management':
330 return 'mgmt'
331 elif network == 'default':
332 raise F5ModuleError(
333 "'default' is not a valid option for this version of BIG-IP. "
334 "Use either 'management', 'or 'other' instead."
335 )
336 else:
337 return network
338
339
340 class V2Parameters(Parameters):
341 updatables = [
342 'snmp_version',
343 'community',
344 'destination',
345 'port',
346 'network',
347 ]
348
349 returnables = [
350 'snmp_version',
351 'community',
352 'destination',
353 'port',
354 'network',
355 ]
356
357 api_attributes = [
358 'version',
359 'community',
360 'host',
361 'port',
362 'network',
363 ]
364
365 @property
366 def network(self):
367 if self._values['network'] is None:
368 return None
369 network = str(self._values['network'])
370 if network == 'management':
371 return 'mgmt'
372 elif network == 'default':
373 return ''
374 else:
375 return network
376
377
378 class V1Parameters(Parameters):
379 updatables = [
380 'snmp_version',
381 'community',
382 'destination',
383 'port',
384 ]
385
386 returnables = [
387 'snmp_version',
388 'community',
389 'destination',
390 'port',
391 ]
392
393 api_attributes = [
394 'version',
395 'community',
396 'host',
397 'port',
398 ]
399
400 @property
401 def network(self):
402 return None
403
404
405 class ModuleManager(object):
406 def __init__(self, *args, **kwargs):
407 self.module = kwargs.get('module', None)
408 self.client = F5RestClient(**self.module.params)
409 self.kwargs = kwargs
410
411 def exec_module(self):
412 if self.is_version_without_network():
413 manager = V1Manager(**self.kwargs)
414 elif self.is_version_with_default_network():
415 manager = V2Manager(**self.kwargs)
416 else:
417 manager = V3Manager(**self.kwargs)
418
419 return manager.exec_module()
420
421 def is_version_without_network(self):
422 """Is current BIG-IP version missing "network" value support
423
424 Returns:
425 bool: True when it is missing. False otherwise.
426 """
427 version = tmos_version(self.client)
428 if Version(version) < Version('12.1.0'):
429 return True
430 else:
431 return False
432
433 def is_version_with_default_network(self):
434 """Is current BIG-IP version missing "default" network value support
435
436 Returns:
437 bool: True when it is missing. False otherwise.
438 """
439 version = tmos_version(self.client)
440 if Version(version) < Version('13.1.0'):
441 return True
442 else:
443 return False
444
445
446 class BaseManager(object):
447 def __init__(self, *args, **kwargs):
448 self.module = kwargs.get('module', None)
449 self.client = F5RestClient(**self.module.params)
450 self.have = None
451
452 def exec_module(self):
453 start = datetime.now().isoformat()
454 version = tmos_version(self.client)
455 changed = False
456 result = dict()
457 state = self.want.state
458
459 if state == "present":
460 changed = self.present()
461 elif state == "absent":
462 changed = self.absent()
463
464 changes = self.changes.to_return()
465 result.update(**changes)
466 result.update(dict(changed=changed))
467 send_teem(start, self.client, self.module, version)
468 return result
469
470 def present(self):
471 if self.exists():
472 return self.update()
473 else:
474 return self.create()
475
476 def absent(self):
477 if self.exists():
478 return self.remove()
479 return False
480
481 def remove(self):
482 if self.module.check_mode:
483 return True
484 self.remove_from_device()
485 if self.exists():
486 raise F5ModuleError("Failed to delete the snmp trap")
487 return True
488
489 def create(self):
490 self._set_changed_options()
491 if self.module.check_mode:
492 return True
493 if all(getattr(self.want, v) is None for v in self.required_resources):
494 raise F5ModuleError(
495 "You must specify at least one of "
496 ', '.join(self.required_resources)
497 )
498 self.create_on_device()
499 return True
500
501 def should_update(self):
502 result = self._update_changed_options()
503 if result:
504 return True
505 return False
506
507 def update(self):
508 self.have = self.read_current_from_device()
509 if not self.should_update():
510 return False
511 if self.module.check_mode:
512 return True
513 self.update_on_device()
514 return True
515
516 def exists(self):
517 uri = "https://{0}:{1}/mgmt/tm/sys/snmp/traps/{2}".format(
518 self.client.provider['server'],
519 self.client.provider['server_port'],
520 transform_name(self.want.partition, self.want.name)
521 )
522 resp = self.client.api.get(uri)
523 try:
524 response = resp.json()
525 except ValueError as ex:
526 raise F5ModuleError(str(ex))
527
528 if resp.status == 404 or 'code' in response and response['code'] == 404:
529 return False
530 if resp.status in [200, 201] or 'code' in response and response['code'] in [200, 201]:
531 return True
532
533 errors = [401, 403, 409, 500, 501, 502, 503, 504]
534
535 if resp.status in errors or 'code' in response and response['code'] in errors:
536 if 'message' in response:
537 raise F5ModuleError(response['message'])
538 else:
539 raise F5ModuleError(resp.content)
540
541 def update_on_device(self):
542 params = self.want.api_params()
543 uri = "https://{0}:{1}/mgmt/tm/sys/snmp/traps/{2}".format(
544 self.client.provider['server'],
545 self.client.provider['server_port'],
546 transform_name(self.want.partition, self.want.name)
547 )
548 resp = self.client.api.patch(uri, json=params)
549 try:
550 response = resp.json()
551 except ValueError as ex:
552 raise F5ModuleError(str(ex))
553
554 if 'code' in response and response['code'] == 400:
555 if 'message' in response:
556 raise F5ModuleError(response['message'])
557 else:
558 raise F5ModuleError(resp.content)
559
560 def create_on_device(self):
561 params = self.want.api_params()
562 params['name'] = self.want.name
563 params['partition'] = self.want.partition
564 uri = "https://{0}:{1}/mgmt/tm/sys/snmp/traps/".format(
565 self.client.provider['server'],
566 self.client.provider['server_port'],
567 )
568 resp = self.client.api.post(uri, json=params)
569 try:
570 response = resp.json()
571 except ValueError as ex:
572 raise F5ModuleError(str(ex))
573
574 if 'code' in response and response['code'] in [400, 403]:
575 if 'message' in response:
576 raise F5ModuleError(response['message'])
577 else:
578 raise F5ModuleError(resp.content)
579
580 def remove_from_device(self):
581 uri = "https://{0}:{1}/mgmt/tm/sys/snmp/traps/{2}".format(
582 self.client.provider['server'],
583 self.client.provider['server_port'],
584 transform_name(self.want.partition, self.want.name)
585 )
586 resp = self.client.api.delete(uri)
587 if resp.status == 200:
588 return True
589
590
591 class V3Manager(BaseManager):
592 def __init__(self, *args, **kwargs):
593 super(V3Manager, self).__init__(**kwargs)
594 self.required_resources = [
595 'version', 'community', 'destination', 'port', 'network', 'security_name', 'auth_protocol', 'auth_password',
596 'security_level', 'privacy_protocol', 'privacy_password'
597 ]
598 self.want = V3Parameters(params=self.module.params)
599 self.changes = V3Parameters()
600
601 def _set_changed_options(self):
602 changed = {}
603 for key in V3Parameters.returnables:
604 if getattr(self.want, key) is not None:
605 changed[key] = getattr(self.want, key)
606 if changed:
607 self.changes = V3Parameters(params=changed)
608
609 def _update_changed_options(self):
610 changed = {}
611 for key in V3Parameters.updatables:
612 if getattr(self.want, key) is not None:
613 attr1 = getattr(self.want, key)
614 attr2 = getattr(self.have, key)
615 if attr1 != attr2:
616 changed[key] = attr1
617 if changed:
618 self.changes = V3Parameters(params=changed)
619 return True
620 return False
621
622 def read_current_from_device(self):
623 uri = "https://{0}:{1}/mgmt/tm/sys/snmp/traps/{2}".format(
624 self.client.provider['server'],
625 self.client.provider['server_port'],
626 transform_name(self.want.partition, self.want.name)
627 )
628 resp = self.client.api.get(uri)
629 try:
630 response = resp.json()
631 except ValueError as ex:
632 raise F5ModuleError(str(ex))
633
634 if 'code' in response and response['code'] == 400:
635 if 'message' in response:
636 raise F5ModuleError(response['message'])
637 else:
638 raise F5ModuleError(resp.content)
639 return V3Parameters(params=response)
640
641
642 class V2Manager(BaseManager):
643 def __init__(self, *args, **kwargs):
644 super(V2Manager, self).__init__(**kwargs)
645 self.required_resources = [
646 'version', 'community', 'destination', 'port', 'network'
647 ]
648 self.want = V2Parameters(params=self.module.params)
649 self.changes = V2Parameters()
650
651 def _set_changed_options(self):
652 changed = {}
653 for key in V2Parameters.returnables:
654 if getattr(self.want, key) is not None:
655 changed[key] = getattr(self.want, key)
656 if changed:
657 self.changes = V2Parameters(params=changed)
658
659 def _update_changed_options(self):
660 changed = {}
661 for key in V2Parameters.updatables:
662 if getattr(self.want, key) is not None:
663 attr1 = getattr(self.want, key)
664 attr2 = getattr(self.have, key)
665 if attr1 != attr2:
666 changed[key] = attr1
667 if changed:
668 self.changes = V2Parameters(params=changed)
669 return True
670 return False
671
672 def read_current_from_device(self):
673 uri = "https://{0}:{1}/mgmt/tm/sys/snmp/traps/{2}".format(
674 self.client.provider['server'],
675 self.client.provider['server_port'],
676 transform_name(self.want.partition, self.want.name)
677 )
678 resp = self.client.api.get(uri)
679 try:
680 response = resp.json()
681 except ValueError as ex:
682 raise F5ModuleError(str(ex))
683
684 if 'code' in response and response['code'] == 400:
685 if 'message' in response:
686 raise F5ModuleError(response['message'])
687 else:
688 raise F5ModuleError(resp.content)
689 self._ensure_network(response)
690 return V2Parameters(params=response)
691
692 def _ensure_network(self, result):
693 # BIG-IP's value for "default" is that the key does not
694 # exist. This conflicts with our purpose of having a key
695 # not exist (which we equate to "i dont want to change that"
696 # therefore, if we load the information from BIG-IP and
697 # find that there is no 'network' key, that is BIG-IP's
698 # way of saying that the network value is "default"
699 if 'network' not in result:
700 result['network'] = 'default'
701
702
703 class V1Manager(BaseManager):
704 def __init__(self, *args, **kwargs):
705 super(V1Manager, self).__init__(**kwargs)
706 self.required_resources = [
707 'version', 'community', 'destination', 'port'
708 ]
709 self.want = V1Parameters(params=self.module.params)
710 self.changes = V1Parameters()
711
712 def _set_changed_options(self):
713 changed = {}
714 for key in V1Parameters.returnables:
715 if getattr(self.want, key) is not None:
716 changed[key] = getattr(self.want, key)
717 if changed:
718 self.changes = V1Parameters(params=changed)
719
720 def _update_changed_options(self):
721 changed = {}
722 for key in V1Parameters.updatables:
723 if getattr(self.want, key) is not None:
724 attr1 = getattr(self.want, key)
725 attr2 = getattr(self.have, key)
726 if attr1 != attr2:
727 changed[key] = attr1
728 if changed:
729 self.changes = V1Parameters(params=changed)
730 return True
731 return False
732
733 def read_current_from_device(self):
734 uri = "https://{0}:{1}/mgmt/tm/sys/snmp/traps/{2}".format(
735 self.client.provider['server'],
736 self.client.provider['server_port'],
737 transform_name(self.want.partition, self.want.name)
738 )
739 resp = self.client.api.get(uri)
740 try:
741 response = resp.json()
742 except ValueError as ex:
743 raise F5ModuleError(str(ex))
744
745 if 'code' in response and response['code'] == 400:
746 if 'message' in response:
747 raise F5ModuleError(response['message'])
748 else:
749 raise F5ModuleError(resp.content)
750 return V1Parameters(params=response)
751
752
753 class ArgumentSpec(object):
754 def __init__(self):
755 self.supports_check_mode = True
756 argument_spec = dict(
757 name=dict(
758 required=True
759 ),
760 snmp_version=dict(
761 choices=['1', '2c', '3']
762 ),
763 community=dict(no_log=True),
764 destination=dict(),
765 security_name=dict(),
766 security_level=dict(
767 choices=['auth-no-privacy', 'auth-privacy']
768 ),
769 auth_protocol=dict(
770 choices=['sha', 'md5']
771 ),
772 auth_password=dict(no_log=True),
773 privacy_protocol=dict(
774 choices=['aes', 'des']
775 ),
776 privacy_password=dict(no_log=True),
777 port=dict(),
778 network=dict(
779 choices=['other', 'management', 'default']
780 ),
781 state=dict(
782 default='present',
783 choices=['absent', 'present']
784 ),
785 partition=dict(
786 default='Common',
787 fallback=(env_fallback, ['F5_PARTITION'])
788 )
789 )
790
791 self.argument_spec = {}
792 self.argument_spec.update(f5_argument_spec)
793 self.argument_spec.update(argument_spec)
794 self.required_if = [
795 ['snmp_version', '3', ['security_name']],
796 ['snmp_version', '3', ['security_level']],
797 ['security_level', 'auth-no-privacy', ['auth_protocol']],
798 ['security_level', 'auth-no-privacy', ['auth_password']],
799 ['security_level', 'auth-privacy', ['auth_protocol']],
800 ['security_level', 'auth-privacy', ['auth_password']],
801 ['security_level', 'auth-privacy', ['privacy_protocol']],
802 ['security_level', 'auth-privacy', ['privacy_password']]
803 ]
804
805
806 def main():
807 spec = ArgumentSpec()
808
809 module = AnsibleModule(
810 argument_spec=spec.argument_spec,
811 supports_check_mode=spec.supports_check_mode,
812 required_if=spec.required_if
813 )
814
815 if not HAS_PACKAGING:
816 module.fail_json(
817 msg=missing_required_lib('packaging'),
818 exception=PACKAGING_IMPORT_ERROR
819 )
820
821 try:
822 mm = ModuleManager(module=module)
823 results = mm.exec_module()
824 module.exit_json(**results)
825 except F5ModuleError as ex:
826 module.fail_json(msg=str(ex))
827
828
829 if __name__ == '__main__':
830 main()