Debian Codegraph @

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

raw symbols SCIP
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3 #
4 # Copyright: (c) 2019, 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_cgnat_lsn_pool
13 short_description: Manage CGNAT LSN Pools
14 description:
15 - Manage CGNAT LSN (Large Scale NAT) Pools.
16 version_added: "1.0.0"
17 options:
18 name:
19 description:
20 - Specifies the name of the LSN pool to manage.
21 type: str
22 required: True
23 description:
24 description:
25 - User created LSN pool description.
26 type: str
27 client_conn_limit:
28 description:
29 - Specifies the maximum number of simultaneous translated connections a client or subscriber is allowed to have.
30 - Valid range of values is between C(0) and C(4294967295) inclusive.
31 type: int
32 harpin_mode:
33 description:
34 - Enables or disables hairpinning for incoming connections to active translation end-points.
35 type: bool
36 icmp_echo:
37 description:
38 - Enables or disables ICMP echo on translated addresses.
39 type: bool
40 inbound_connections:
41 description:
42 - Controls whether or not the BIG-IP system supports inbound connections for each outbound mapping.
43 - When C(disabled), system does not support inbound connections for outbound mappings, which prevents
44 Port Control Protocol C(pcp) from functioning.
45 - When C(explicit), the system supports inbound connections for explicit outbound mappings.
46 - When C(automatic) the system supports inbound connections for every outbound mapping as it gets used.
47 type: str
48 choices:
49 - disabled
50 - explicit
51 - automatic
52 mode:
53 description:
54 - Specifies the translation address mapping mode.
55 - The C(napt) mode provides standard address and port translation allowing multiple clients in a private network
56 to access remote networks using the single IP address assigned to their router.
57 - The C(deterministic) address translation mode provides address translation that eliminates the logging of every
58 address mapping, while still allowing internal client address tracking using only an external address and port,
59 and a destination address and port.
60 - The C(pba) mode logs the allocation and release of port blocks for subscriber translation requests,
61 instead of separately logging each translation request.
62 type: str
63 choices:
64 - napt
65 - deterministic
66 - pba
67 persistence_mode:
68 description:
69 - Specifies the persistence settings for LSN translation entries.
70 - When C(address), the translation attempts to reuse the address mapping, but not the port mapping.
71 - When C(address-port), the translation attempts to reuse both the address and port mapping for subsequent
72 packets sent from the same internal IP address and port.
73 - When C(none), peristence is disabled.
74 type: str
75 choices:
76 - address
77 - address-port
78 - none
79 persistence_timeout:
80 description:
81 - Specifies the persistence timeout value for LSN translation entries.
82 - "If a particular mapping is unused for this length of time, the mapping expires and the public-side address/port
83 pair is free for use in other mappings."
84 - Valid range of values is between C(0) and C(31536000) inclusive.
85 type: int
86 route_advertisement:
87 description:
88 - Specifies whether the translation addresses are passed to the Advanced Routing Module
89 for advertisement through dynamic routing protocols.
90 type: bool
91 pba_block_idle_timeout:
92 description:
93 - Specifies the timeout duration subsequent to the point when the port block becomes idle.
94 - Valid range of values is between C(0) and C(4294967295) inclusive."
95 type: int
96 pba_block_lifetime:
97 description:
98 - Specifies the timeout for the port block, after which the block is not used for new port allocations.
99 - Valid range of values is between C(0) and C(4294967295) inclusive.
100 - The value of C(0) corresponds to an infinite timeout.
101 type: int
102 pba_block_size:
103 description:
104 - Specifies the number of ports in a block.
105 - Valid range of values is between C(0) and C(65535) inclusive.
106 - The C(pba_block_size) value should be less than or equal to the LSN pool range, i.e the range of ports defined by
107 C(port_range_low) and C(port_range_high) values.
108 type: int
109 pba_client_block_limit:
110 description:
111 - Specifies the number of blocks that can be assigned to a single subscriber IP address.
112 type: int
113 pba_zombie_timeout:
114 description:
115 - Specifies the timeout duration for a zombie port block, which is a timed out port block with one or more active
116 connections. When the timeout duration expires, connections using the zombie block are killed and the zombie
117 port block becomes an available port block.
118 - The value of C(0) corresponds to an infinite timeout.
119 - System ignores this parameter value if C(pba_block_lifetime) is C(0).
120 type: int
121 port_range_low:
122 description:
123 - Specifies the low end of the range of port numbers available for use with translation IP addresses.
124 - The C(port_range_low) must always be lower or equal to C(port_range_high) value.
125 - Valid range of values is between C(0) and C(65535) inclusive.
126 type: int
127 port_range_high:
128 description:
129 - Specifies the high end of the range of port numbers available for use with translation IP addresses.
130 - The C(port_range_high) must always be higher or equal to C(port_range_high) value.
131 - Valid range of values is between C(0) and C(65535) inclusive.
132 type: int
133 egress_intf_enabled:
134 description:
135 - Specifies how the system handles address translation on the interfaces specified in C(egress_interfaces).
136 - When set to C(true), source address translation is allowed only on the specified C(egress_interfaces).
137 - When set to C(false), source address translation is disabled on the specified C(egress_interfaces).
138 type: bool
139 egress_interfaces:
140 description:
141 - Specifies the set of interfaces on which the source address translation is allowed or disallowed,
142 as determined by the C(egress_intf_enabled) setting.
143 type: list
144 elements: str
145 members:
146 description:
147 - Specifies the set of translation IP addresses available in the pool. This is a collection of IP prefixes with
148 their prefix lengths.
149 - All public-side addresses come from the addresses in this group of subnets. Members of two or more deterministic
150 LSN pools must not overlap. Every external address used for deterministic mapping must occur only in one LSN
151 pool.
152 type: list
153 elements: str
154 backup_members:
155 description:
156 - Specifies translation IP addresses available for backup members, which are used by Deterministic translation
157 mode if C(deterministic) mode translation fails and falls back to C(napt) mode.
158 - This is a collection of IP prefixes with their prefix lengths.
159 type: list
160 elements: str
161 log_profile:
162 description:
163 - Specifies the name of the logging profile the pool uses.
164 type: str
165 log_publisher:
166 description:
167 - Specifies the name of the log publisher that logs translation events.
168 type: str
169 partition:
170 description:
171 - Device partition on which to manage resources.
172 type: str
173 default: Common
174 state:
175 description:
176 - When C(state) is C(present), ensures the LSN pool exists.
177 - When C(state) is C(absent), ensures the LSN pool is removed.
178 type: str
179 choices:
180 - present
181 - absent
182 default: present
183 notes:
184 - Requires CGNAT is licensed and enabled on BIG-IP.
185 extends_documentation_fragment: f5networks.f5_modules.f5
186 author:
187 - Wojciech Wypior (@wojtek0806)
188 '''
189
190 EXAMPLES = r'''
191 - name: Create an lsn pool
192 bigip_cgnat_lsn_pool:
193 name: foo
194 mode: napt
195 client_conn_limit: 100
196 log_profile: foo_profile
197 log_publisher: foo_publisher
198 members:
199 - 10.1.1.0/24
200 provider:
201 password: secret
202 server: lb.mydomain.com
203 user: admin
204 delegate_to: localhost
205
206 - name: Update lsn pool
207 bigip_cgnat_lsn_pool:
208 name: foo
209 mode: pba
210 pba_block_size: 128
211 pba_block_lifetime: 7200
212 pba_block_idle_timeout: 1800
213 pba_zombie_timeout: 900
214 log_profile: foo_profile
215 log_publisher: foo_publisher
216 provider:
217 password: secret
218 server: lb.mydomain.com
219 user: admin
220 delegate_to: localhost
221
222 - name: Remove lsn pool
223 bigip_cgnat_lsn_pool:
224 name: foo
225 state: absent
226 provider:
227 password: secret
228 server: lb.mydomain.com
229 user: admin
230 delegate_to: localhost
231 '''
232
233 RETURN = r'''
234 description:
235 description: User created LSN pool description.
236 returned: changed
237 type: str
238 sample: some description
239 client_conn_limit:
240 description: The maximum number of simultaneous translated connections a client or subscriber is allowed to have.
241 returned: changed
242 type: int
243 sample: 50
244 harpin_mode:
245 description: Enables or disables hairpinning for incoming connections to active translation end-points.
246 returned: changed
247 type: bool
248 sample: true
249 icmp_echo:
250 description: Enables or disables ICMP echo on translated addresses.
251 returned: changed
252 type: bool
253 sample: false
254 inbound_connections:
255 description: Controls BIG-IP system support of inbound connections for each outbound mapping.
256 returned: changed
257 type: str
258 sample: explicit
259 mode:
260 description: Specifies the translation address mapping mode.
261 returned: changed
262 type: str
263 sample: napt
264 persistence_mode:
265 description: Specifies the persistence settings for LSN translation entries.
266 returned: changed
267 type: str
268 sample: address
269 persistence_timeout:
270 description: Specifies the persistence timeout value for LSN translation entries.
271 returned: changed
272 type: int
273 sample: 500
274 route_advertisement:
275 description: Specifies whether the translation addresses are advertised through dynamic routing protocols.
276 returned: changed
277 type: bool
278 sample: true
279 pba_block_idle_timeout:
280 description: The timeout duration subsequent to the point when the port block becomes idle.
281 returned: changed
282 type: int
283 sample: 3600
284 pba_block_lifetime:
285 description: The timeout for the port block.
286 returned: changed
287 type: int
288 sample: 7200
289 pba_block_size:
290 description: The number of ports in a block.
291 returned: changed
292 type: int
293 sample: 128
294 pba_client_block_limit:
295 description: The number of blocks that can be assigned to a single subscriber IP address.
296 returned: changed
297 type: int
298 sample: 3
299 pba_zombie_timeout:
300 description: The timeout duration for a zombie port block.
301 returned: changed
302 type: int
303 sample: 180
304 port_range_low:
305 description: The low end of the range of port numbers available for use with translation IP addresses.
306 returned: changed
307 type: int
308 sample: 1025
309 port_range_high:
310 description: The high end of the range of port numbers available for use with translation IP addresses.
311 returned: changed
312 type: int
313 sample: 65535
314 egress_intf_enabled:
315 description: Specifies how the system handles address translation on the egress interfaces.
316 returned: changed
317 type: bool
318 sample: false
319 egress_interfaces:
320 description: The set of interfaces on which source address translation is allowed or disallowed.
321 returned: changed
322 type: list
323 sample: ['/Common/tunnel1', '/Common/tunnel2']
324 members:
325 description: The set of translation IP addresses available in the pool.
326 returned: changed
327 type: list
328 sample: ['/Common/10.10.10.0/24', '/Common/11.11.11.0/25']
329 backup_members:
330 description: The translation IP addresses available for backup members.
331 returned: changed
332 type: list
333 sample: ['/Common/10.10.10.0/24', '/Common/11.11.11.0/25']
334 log_profile:
335 description: The name of the logging profile the pool uses.
336 returned: changed
337 type: str
338 sample: /Common/foo_log_profile
339 log_publisher:
340 description: The name of the log publisher that logs translation events.
341 returned: changed
342 type: list
343 sample: /Common/publisher_1
344 '''
345 from datetime import datetime
346
347 from ansible.module_utils.basic import (
348 AnsibleModule, env_fallback
349 )
350
351 from ..module_utils.bigip import F5RestClient
352 from ..module_utils.common import (
353 F5ModuleError, AnsibleF5Parameters, f5_argument_spec, flatten_boolean, is_empty_list, fq_name, transform_name
354 )
355 from ..module_utils.compare import cmp_simple_list
356 from ..module_utils.icontrol import tmos_version
357 from ..module_utils.teem import send_teem
358
359
360 class Parameters(AnsibleF5Parameters):
361 api_map = {
362 'clientConnectionLimit': 'client_conn_limit',
363 'hairpinMode': 'harpin_mode',
364 'routeAdvertisement': 'route_advertisement',
365 'egressInterfaces': 'egress_interfaces',
366 'icmpEcho': 'icmp_echo',
367 'inboundConnections': 'inbound_connections',
368 'backupMembers': 'backup_members',
369 'portBlockAllocation': 'port_block_allocation',
370 'translationPortRange': 'translation_port_range',
371 'egressInterfacesEnabled': 'egress_interfaces_enabled',
372 'egressInterfacesDisabled': 'egress_interfaces_disabled',
373 'logProfile': 'log_profile',
374 'logPublisher': 'log_publisher',
375 }
376
377 api_attributes = [
378 'clientConnectionLimit',
379 'egressInterfacesEnabled',
380 'egressInterfacesDisabled',
381 'hairpinMode',
382 'icmpEcho',
383 'inboundConnections',
384 'mode',
385 'persistence',
386 'portBlockAllocation',
387 'routeAdvertisement',
388 'translationPortRange',
389 'egressInterfaces',
390 'members',
391 'backupMembers',
392 'logProfile',
393 'logPublisher',
394 'description',
395 ]
396
397 returnables = [
398 'client_conn_limit',
399 'harpin_mode',
400 'icmp_echo',
401 'inbound_connections',
402 'mode',
403 'persistence_mode',
404 'persistence_timeout',
405 'route_advertisement',
406 'pba_block_idle_timeout',
407 'pba_block_lifetime',
408 'pba_block_size',
409 'pba_client_block_limit',
410 'pba_zombie_timeout',
411 'port_range_low',
412 'port_range_high',
413 'egress_intf_enabled',
414 'egress_interfaces',
415 'translation_port_range',
416 'members',
417 'backup_members',
418 'log_profile',
419 'log_publisher',
420 'description',
421 ]
422
423 updatables = [
424 'client_conn_limit',
425 'harpin_mode',
426 'icmp_echo',
427 'inbound_connections',
428 'mode',
429 'persistence_mode',
430 'persistence_timeout',
431 'route_advertisement',
432 'translation_port_range',
433 'port_range_low',
434 'port_range_high',
435 'pba_block_idle_timeout',
436 'pba_block_lifetime',
437 'pba_block_size',
438 'pba_client_block_limit',
439 'pba_zombie_timeout',
440 'egress_intf_enabled',
441 'egress_interfaces',
442 'members',
443 'backup_members',
444 'log_profile',
445 'log_publisher',
446 'description',
447 ]
448
449
450 class ApiParameters(Parameters):
451 @property
452 def pba_block_idle_timeout(self):
453 if self._values['port_block_allocation'] is None:
454 return None
455 return self._values['port_block_allocation']['blockIdleTimeout']
456
457 @property
458 def pba_block_lifetime(self):
459 if self._values['port_block_allocation'] is None:
460 return None
461 return self._values['port_block_allocation']['blockLifetime']
462
463 @property
464 def pba_block_size(self):
465 if self._values['port_block_allocation'] is None:
466 return None
467 return self._values['port_block_allocation']['blockSize']
468
469 @property
470 def pba_client_block_limit(self):
471 if self._values['port_block_allocation'] is None:
472 return None
473 return self._values['port_block_allocation']['clientBlockLimit']
474
475 @property
476 def pba_zombie_timeout(self):
477 if self._values['port_block_allocation'] is None:
478 return None
479 return self._values['port_block_allocation']['zombieTimeout']
480
481 @property
482 def port_range_low(self):
483 if self._values['translation_port_range'] is None:
484 return None
485 return int(self._values['translation_port_range'].split('-')[0])
486
487 @property
488 def port_range_high(self):
489 if self._values['translation_port_range'] is None:
490 return None
491 return int(self._values['translation_port_range'].split('-')[1])
492
493 @property
494 def egress_intf_enabled(self):
495 if self._values['egress_interfaces_enabled'] is None and self._values['egress_interfaces_disabled'] is True:
496 return 'no'
497 if self._values['egress_interfaces_disabled'] is None and self._values['egress_interfaces_enabled'] is True:
498 return 'yes'
499
500 @property
501 def persistence_mode(self):
502 if self._values['persistence'] is None:
503 return None
504 return self._values['persistence']['mode']
505
506 @property
507 def persistence_timeout(self):
508 if self._values['persistence'] is None:
509 return None
510 return self._values['persistence']['timeout']
511
512
513 class ModuleParameters(Parameters):
514 @property
515 def client_conn_limit(self):
516 if self._values['client_conn_limit'] is None:
517 return None
518 if 0 <= self._values['client_conn_limit'] <= 4294967295:
519 return self._values['client_conn_limit']
520 raise F5ModuleError(
521 "Valid 'client_conn_limit' must be in range 0 - 4294967295."
522 )
523
524 @property
525 def harpin_mode(self):
526 result = flatten_boolean(self._values['harpin_mode'])
527 if result is None:
528 return None
529 if result == 'yes':
530 return 'enabled'
531 return 'disabled'
532
533 @property
534 def icmp_echo(self):
535 result = flatten_boolean(self._values['icmp_echo'])
536 if result is None:
537 return None
538 if result == 'yes':
539 return 'enabled'
540 return 'disabled'
541
542 @property
543 def persistence_timeout(self):
544 if self._values['persistence_timeout'] is None:
545 return None
546 if 0 <= self._values['persistence_timeout'] <= 31536000:
547 return self._values['persistence_timeout']
548 raise F5ModuleError(
549 "Valid 'persistence_timeout' must be in range 0 - 31536000."
550 )
551
552 @property
553 def route_advertisement(self):
554 result = flatten_boolean(self._values['route_advertisement'])
555 if result is None:
556 return None
557 if result == 'yes':
558 return 'enabled'
559 return 'disabled'
560
561 @property
562 def pba_block_idle_timeout(self):
563 if self._values['pba_block_idle_timeout'] is None:
564 return None
565 if 0 <= self._values['pba_block_idle_timeout'] <= 4294967295:
566 return self._values['pba_block_idle_timeout']
567 raise F5ModuleError(
568 "Valid 'pba_block_idle_timeout' must be in range 0 - 4294967295."
569 )
570
571 @property
572 def pba_block_lifetime(self):
573 if self._values['pba_block_lifetime'] is None:
574 return None
575 if 0 <= self._values['pba_block_lifetime'] <= 4294967295:
576 return self._values['pba_block_lifetime']
577 raise F5ModuleError(
578 "Valid 'pba_block_lifetime' must be in range 0 - 4294967295."
579 )
580
581 @property
582 def pba_block_size(self):
583 if self._values['pba_block_size'] is None:
584 return None
585 if 0 <= self._values['pba_block_size'] <= 65535:
586 return self._values['pba_block_size']
587 raise F5ModuleError(
588 "Valid 'pba_block_size' must be in range 0 - 65535."
589 )
590
591 @property
592 def pba_client_block_limit(self):
593 if self._values['pba_client_block_limit'] is None:
594 return None
595 if 0 <= self._values['pba_client_block_limit'] <= 65535:
596 return self._values['pba_client_block_limit']
597 raise F5ModuleError(
598 "Valid 'pba_client_block_limit' must be in range 0 - 65535."
599 )
600
601 @property
602 def pba_zombie_timeout(self):
603 if self._values['pba_zombie_timeout'] is None:
604 return None
605 if 0 <= self._values['pba_zombie_timeout'] <= 4294967295:
606 return self._values['pba_zombie_timeout']
607 raise F5ModuleError(
608 "Valid 'pba_zombie_timeout' must be in range 0 - 4294967295."
609 )
610
611 @property
612 def port_range_low(self):
613 if self._values['port_range_low'] is None:
614 return None
615 high = self.port_range_high
616 if 0 <= self._values['port_range_low'] <= 65535:
617 if high:
618 if high < self._values['port_range_low']:
619 raise F5ModuleError(
620 "The 'port_range_low' value: {0} is lower than 'port_range_high' value: {1}".format(
621 self._values['port_range_low'], high)
622 )
623 return self._values['port_range_low']
624 raise F5ModuleError(
625 "Valid 'port_range_low' must be in range 0 - 65535."
626 )
627
628 @property
629 def translation_port_range(self):
630 if self._values['port_range_low'] is None:
631 return None
632 result = '{0}-{1}'.format(self.port_range_low, self.port_range_high)
633 return result
634
635 @property
636 def port_range_high(self):
637 if self._values['port_range_high'] is None:
638 return None
639 if 0 <= self._values['port_range_high'] <= 65535:
640 return self._values['port_range_high']
641 raise F5ModuleError(
642 "Valid 'port_range_high' must be in range 0 - 65535."
643 )
644
645 @property
646 def egress_intf_enabled(self):
647 result = flatten_boolean(self._values['egress_intf_enabled'])
648 return result
649
650 @property
651 def egress_interfaces(self):
652 if self._values['egress_interfaces'] is None:
653 return None
654 if is_empty_list(self._values['egress_interfaces']):
655 return ''
656 result = []
657 for interface in self._values['egress_interfaces']:
658 result.append(fq_name(self.partition, interface))
659 return result
660
661 @property
662 def log_profile(self):
663 if self._values['log_profile'] is None:
664 return None
665 if self._values['log_profile'] in ['', 'none']:
666 return ''
667 result = fq_name(self.partition, self._values['log_profile'])
668 return result
669
670 @property
671 def log_publisher(self):
672 if self._values['log_publisher'] is None:
673 return None
674 if self._values['log_publisher'] in ['', 'none']:
675 return ''
676 result = fq_name(self.partition, self._values['log_publisher'])
677 return result
678
679 @property
680 def members(self):
681 if self._values['members'] is None:
682 return None
683 if is_empty_list(self._values['members']):
684 return ''
685 return self._values['members']
686
687 @property
688 def backup_members(self):
689 if self._values['backup_members'] is None:
690 return None
691 if is_empty_list(self._values['backup_members']):
692 return ''
693 return self._values['backup_members']
694
695
696 class Changes(Parameters):
697 def to_return(self):
698 result = {}
699 try:
700 for returnable in self.returnables:
701 result[returnable] = getattr(self, returnable)
702 result = self._filter_params(result)
703 except Exception:
704 raise
705 return result
706
707
708 class UsableChanges(Changes):
709 @property
710 def persistence(self):
711 to_filter = dict(
712 mode=self._values['persistence_mode'],
713 timeout=self._values['persistence_timeout'],
714 )
715 result = self._filter_params(to_filter)
716 if result:
717 return result
718
719 @property
720 def port_block_allocation(self):
721 to_filter = dict(
722 blockIdleTimeout=self._values['pba_block_idle_timeout'],
723 blockLifetime=self._values['pba_block_lifetime'],
724 blockSize=self._values['pba_block_size'],
725 clientBlockLimit=self._values['pba_client_block_limit'],
726 zombieTimeout=self._values['pba_zombie_timeout'],
727 )
728 result = self._filter_params(to_filter)
729 if result:
730 return result
731
732 @property
733 def egress_interfaces_enabled(self):
734 if self._values['egress_intf_enabled'] is None:
735 return None
736 if self._values['egress_intf_enabled'] == 'yes':
737 return True
738
739 @property
740 def egress_interfaces_disabled(self):
741 if self._values['egress_intf_enabled'] is None:
742 return None
743 if self._values['egress_intf_enabled'] == 'no':
744 return True
745
746
747 class ReportableChanges(Changes):
748 returnables = [
749 'client_conn_limit',
750 'harpin_mode',
751 'icmp_echo',
752 'inbound_connections',
753 'mode',
754 'persistence_mode',
755 'persistence_timeout',
756 'route_advertisement',
757 'pba_block_idle_timeout',
758 'pba_block_lifetime',
759 'pba_block_size',
760 'pba_client_block_limit',
761 'pba_zombie_timeout',
762 'port_range_low',
763 'port_range_high',
764 'egress_intf_enabled',
765 'egress_interfaces',
766 'members',
767 'backup_members',
768 'log_profile',
769 'log_publisher',
770 'description',
771 ]
772
773 @property
774 def route_advertisement(self):
775 result = flatten_boolean(self._values['route_advertisement'])
776 return result
777
778 @property
779 def icmp_echo(self):
780 result = flatten_boolean(self._values['icmp_echo'])
781 return result
782
783 @property
784 def harpin_mode(self):
785 result = flatten_boolean(self._values['harpin_mode'])
786 return result
787
788
789 class Difference(object):
790 def __init__(self, want, have=None):
791 self.want = want
792 self.have = have
793
794 def compare(self, param):
795 try:
796 result = getattr(self, param)
797 return result
798 except AttributeError:
799 return self.__default(param)
800
801 def __default(self, param):
802 attr1 = getattr(self.want, param)
803 try:
804 attr2 = getattr(self.have, param)
805 if attr1 != attr2:
806 return attr1
807 except AttributeError:
808 return attr1
809
810 @property
811 def translation_port_range(self):
812 if self.want.port_range_low is None:
813 return None
814 if self.want.port_range_low != self.have.port_range_low:
815 result = "{0}-{1}".format(self.want.port_range_low, self.want.port_range_high)
816 return result
817 if self.want.port_range_high != self.have.port_range_high:
818 result = "{0}-{1}".format(self.want.port_range_low, self.want.port_range_high)
819 return result
820 return None
821
822 @property
823 def members(self):
824 return cmp_simple_list(self.want.members, self.have.members)
825
826 @property
827 def backup_members(self):
828 return cmp_simple_list(self.want.backup_members, self.have.backup_members)
829
830 @property
831 def egress_interfaces(self):
832 return cmp_simple_list(self.want.egress_interfaces, self.have.egress_interfaces)
833
834 @property
835 def log_profile(self):
836 if self.want.log_profile is None:
837 return None
838 if self.want.log_profile == '' and self.have.log_profile in [None, 'none']:
839 return None
840 if self.want.log_profile == '':
841 if self.have.log_publisher not in [None, 'none'] and self.want.log_publisher is None:
842 raise F5ModuleError(
843 "The log_profile cannot be removed if log_publisher is defined on device."
844 )
845 if self.want.log_profile != '':
846 if self.want.log_publisher is None and self.have.log_publisher in [None, 'none']:
847 raise F5ModuleError(
848 "The log_profile cannot be specified without an existing valid log_publisher."
849 )
850 if self.want.log_profile != self.have.log_profile:
851 return self.want.log_profile
852
853 @property
854 def log_publisher(self):
855 if self.want.log_publisher is None:
856 return None
857 if self.want.log_publisher == '' and self.have.log_publisher in [None, 'none']:
858 return None
859 if self.want.log_publisher == '':
860 if self.want.log_profile is None and self.have.log_profile not in [None, 'none']:
861 raise F5ModuleError(
862 "The log_publisher cannot be removed if log_profile is defined on device."
863 )
864 if self.want.log_publisher != self.have.log_publisher:
865 return self.want.log_publisher
866
867 @property
868 def description(self):
869 if self.want.description is None:
870 return None
871 if self.have.description in [None, 'none'] and self.want.description == '':
872 return None
873 if self.want.description != self.have.description:
874 return self.want.description
875
876
877 class ModuleManager(object):
878 def __init__(self, *args, **kwargs):
879 self.module = kwargs.get('module', None)
880 self.client = F5RestClient(**self.module.params)
881 self.want = ModuleParameters(params=self.module.params)
882 self.have = ApiParameters()
883 self.changes = UsableChanges()
884
885 def _set_changed_options(self):
886 changed = {}
887 for key in Parameters.returnables:
888 if getattr(self.want, key) is not None:
889 changed[key] = getattr(self.want, key)
890 if changed:
891 self.changes = UsableChanges(params=changed)
892
893 def _update_changed_options(self):
894 diff = Difference(self.want, self.have)
895 updatables = Parameters.updatables
896 changed = dict()
897 for k in updatables:
898 change = diff.compare(k)
899 if change is None:
900 continue
901 else:
902 if isinstance(change, dict):
903 changed.update(change)
904 else:
905 changed[k] = change
906 if changed:
907 self.changes = UsableChanges(params=changed)
908 return True
909 return False
910
911 def _announce_deprecations(self, result):
912 warnings = result.pop('__warnings', [])
913 for warning in warnings:
914 self.client.module.deprecate(
915 msg=warning['msg'],
916 version=warning['version']
917 )
918
919 def exec_module(self):
920 start = datetime.now().isoformat()
921 version = tmos_version(self.client)
922 changed = False
923 result = dict()
924 state = self.want.state
925
926 if state == "present":
927 changed = self.present()
928 elif state == "absent":
929 changed = self.absent()
930
931 reportable = ReportableChanges(params=self.changes.to_return())
932 changes = reportable.to_return()
933 result.update(**changes)
934 result.update(dict(changed=changed))
935 self._announce_deprecations(result)
936 send_teem(start, self.client, self.module, version)
937 return result
938
939 def present(self):
940 if self.exists():
941 return self.update()
942 else:
943 return self.create()
944
945 def absent(self):
946 if self.exists():
947 return self.remove()
948 return False
949
950 def should_update(self):
951 result = self._update_changed_options()
952 if result:
953 return True
954 return False
955
956 def update(self):
957 self.have = self.read_current_from_device()
958 if not self.should_update():
959 return False
960 if self.module.check_mode:
961 return True
962 self.update_on_device()
963 return True
964
965 def remove(self):
966 if self.module.check_mode:
967 return True
968 self.remove_from_device()
969 if self.exists():
970 raise F5ModuleError("Failed to delete the resource.")
971 return True
972
973 def create(self):
974 self._set_changed_options()
975 self.check_create_dependencies()
976 if self.module.check_mode:
977 return True
978 self.create_on_device()
979 return True
980
981 def check_create_dependencies(self):
982 if self.want.log_publisher is None:
983 if self.want.log_profile is not None:
984 raise F5ModuleError(
985 "The 'log_profile' cannot be used without a defined 'log_publisher'."
986 )
987
988 def exists(self):
989 errors = [401, 403, 409, 500, 501, 502, 503, 504]
990 uri = "https://{0}:{1}/mgmt/tm/ltm/lsn-pool/{2}".format(
991 self.client.provider['server'],
992 self.client.provider['server_port'],
993 transform_name(self.want.partition, self.want.name)
994 )
995 resp = self.client.api.get(uri)
996 try:
997 response = resp.json()
998 except ValueError as ex:
999 raise F5ModuleError(str(ex))
1000
1001 if resp.status == 404 or 'code' in response and response['code'] == 404:
1002 return False
1003 if resp.status in [200, 201] or 'code' in response and response['code'] in [200, 201]:
1004 return True
1005
1006 if resp.status in errors or 'code' in response and response['code'] in errors:
1007 if 'message' in response:
1008 raise F5ModuleError(response['message'])
1009 else:
1010 raise F5ModuleError(resp.content)
1011
1012 def create_on_device(self):
1013 params = self.changes.api_params()
1014 params['name'] = self.want.name
1015 params['partition'] = self.want.partition
1016 uri = "https://{0}:{1}/mgmt/tm/ltm/lsn-pool/".format(
1017 self.client.provider['server'],
1018 self.client.provider['server_port'],
1019 )
1020 resp = self.client.api.post(uri, json=params)
1021 try:
1022 response = resp.json()
1023 except ValueError as ex:
1024 raise F5ModuleError(str(ex))
1025
1026 if resp.status in [200, 201] or 'code' in response and response['code'] in [200, 201]:
1027 return True
1028 raise F5ModuleError(resp.content)
1029
1030 def update_on_device(self):
1031 params = self.changes.api_params()
1032 uri = "https://{0}:{1}/mgmt/tm/ltm/lsn-pool/{2}".format(
1033 self.client.provider['server'],
1034 self.client.provider['server_port'],
1035 transform_name(self.want.partition, self.want.name)
1036 )
1037 resp = self.client.api.patch(uri, json=params)
1038 try:
1039 response = resp.json()
1040 except ValueError as ex:
1041 raise F5ModuleError(str(ex))
1042
1043 if resp.status in [200, 201] or 'code' in response and response['code'] in [200, 201]:
1044 return True
1045 raise F5ModuleError(resp.content)
1046
1047 def remove_from_device(self):
1048 uri = "https://{0}:{1}/mgmt/tm/ltm/lsn-pool/{2}".format(
1049 self.client.provider['server'],
1050 self.client.provider['server_port'],
1051 transform_name(self.want.partition, self.want.name)
1052 )
1053 response = self.client.api.delete(uri)
1054
1055 if response.status in [200, 201]:
1056 return True
1057 raise F5ModuleError(response.content)
1058
1059 def read_current_from_device(self):
1060 uri = "https://{0}:{1}/mgmt/tm/ltm/lsn-pool/{2}".format(
1061 self.client.provider['server'],
1062 self.client.provider['server_port'],
1063 transform_name(self.want.partition, self.want.name)
1064 )
1065 resp = self.client.api.get(uri)
1066 try:
1067 response = resp.json()
1068 except ValueError as ex:
1069 raise F5ModuleError(str(ex))
1070
1071 if resp.status in [200, 201] or 'code' in response and response['code'] in [200, 201]:
1072 return ApiParameters(params=response)
1073 raise F5ModuleError(resp.content)
1074
1075
1076 class ArgumentSpec(object):
1077 def __init__(self):
1078 self.supports_check_mode = True
1079 argument_spec = dict(
1080 name=dict(required=True),
1081 description=dict(),
1082 client_conn_limit=dict(type='int'),
1083 harpin_mode=dict(type='bool'),
1084 icmp_echo=dict(type='bool'),
1085 inbound_connections=dict(choices=['disabled', 'explicit', 'automatic']),
1086 mode=dict(choices=['deterministic', 'pba', 'napt']),
1087 persistence_mode=dict(choices=['address', 'address-port', 'none']),
1088 persistence_timeout=dict(type='int'),
1089 route_advertisement=dict(type='bool'),
1090 pba_block_idle_timeout=dict(type='int'),
1091 pba_block_lifetime=dict(type='int'),
1092 pba_block_size=dict(type='int'),
1093 pba_client_block_limit=dict(type='int'),
1094 pba_zombie_timeout=dict(type='int'),
1095 port_range_low=dict(type='int'),
1096 port_range_high=dict(type='int'),
1097 egress_intf_enabled=dict(type='bool'),
1098 egress_interfaces=dict(
1099 type='list',
1100 elements='str',
1101 ),
1102 members=dict(
1103 type='list',
1104 elements='str',
1105 ),
1106 backup_members=dict(
1107 type='list',
1108 elements='str',
1109 ),
1110 log_profile=dict(),
1111 log_publisher=dict(),
1112 partition=dict(
1113 default='Common',
1114 fallback=(env_fallback, ['F5_PARTITION'])
1115 ),
1116 state=dict(
1117 default='present',
1118 choices=['present', 'absent']
1119 )
1120 )
1121 self.required_together = [
1122 ['port_range_low', 'port_range_high']
1123 ]
1124 self.argument_spec = {}
1125 self.argument_spec.update(f5_argument_spec)
1126 self.argument_spec.update(argument_spec)
1127
1128
1129 def main():
1130 spec = ArgumentSpec()
1131
1132 module = AnsibleModule(
1133 argument_spec=spec.argument_spec,
1134 supports_check_mode=spec.supports_check_mode,
1135 required_together=spec.required_together,
1136 )
1137
1138 try:
1139 mm = ModuleManager(module=module)
1140 results = mm.exec_module()
1141 module.exit_json(**results)
1142 except F5ModuleError as ex:
1143 module.fail_json(msg=str(ex))
1144
1145
1146 if __name__ == '__main__':
1147 main()