Debian Codegraph @

ansible_collections/f5networks/f5_modules/plugins/modules/bigip_snat_translation.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_snat_translation
13 short_description: Manage SNAT translations on a BIG-IP
14 description:
15 - Manage SNAT translations on a BIG-IP system.
16 version_added: "1.0.0"
17 options:
18 address:
19 description:
20 - Specifies the IP address of the SNAT translation. When C(state) is C(present), C(enabled),
21 or C(disabled), this parameter is required.
22 - This parameter cannot be updated after it is set.
23 type: str
24 aliases:
25 - ip
26 arp:
27 description:
28 - If C(true), specifies the NAT sends ARP requests.
29 type: bool
30 connection_limit:
31 description:
32 - Specifies a limit on the number of connections a translation address must reach before it no longer
33 initiates a connection. The default value of C(0) indicates the setting is disabled.
34 - The accepted value range is C(0 - 65535).
35 type: int
36 description:
37 description:
38 - Description of snat-translation. C(none or '') sets a default description of null.
39 type: str
40 ip_idle_timeout:
41 description:
42 - Specifies the amount of time connections to an IP address initiated using a SNAT address are
43 allowed to remain idle before being automatically disconnected. C(indefinite) prevents the connection
44 from timing out.
45 - The accepted value range is C(0 - 4294967295) seconds. Specifying C(indefinite)
46 sets it to the maximum value.
47 type: str
48 name:
49 description:
50 - The name of SNAT translation.
51 type: str
52 required: True
53 partition:
54 description:
55 - Device partition to manage resources on.
56 - Required with state C(absent) when a partition other than Common is used.
57 type: str
58 state:
59 description:
60 - The SNAT translation state. If C(absent), deletes the SNAT translation
61 if it exists. C(present) creates the SNAT translation and enables it.
62 If C(enabled), enables the SNAT translation if it exists. If C(disabled),
63 creates the SNAT translation if needed, and sets the state to C(disabled).
64 type: str
65 choices:
66 - present
67 - absent
68 - enabled
69 - disabled
70 default: present
71 tcp_idle_timeout:
72 description:
73 - Specifies the amount of time that TCP connections initiated using a SNAT address are allowed
74 to remain idle before being automatically disconnected. C(indefinite) prevents the
75 connection from timing out.
76 - The accepted value range is C(0 - 4294967295) seconds. Specifying C(indefinite)
77 sets it to the maximum value.
78 type: str
79 traffic_group:
80 description:
81 - The traffic group for the snat-translation address. When creating a new address,
82 if this value is not specified, the default is C(/Common/traffic-group-1).
83 type: str
84 udp_idle_timeout:
85 description:
86 - Specifies the amount of time UDP connections initiated using a SNAT address are allowed
87 to remain idle before being automatically disconnected. C(indefinite) prevents the connection
88 from timing out.
89 - The accepted value range is C(0 - 4294967295) seconds. Specifying C(indefinite)
90 sets it to the maximum value.
91 type: str
92 extends_documentation_fragment: f5networks.f5_modules.f5
93 author:
94 - Greg Crosby (@crosbygw)
95 - Wojciech Wypior (@wojtek0806)
96 '''
97
98 EXAMPLES = r'''
99 - name: Create a SNAT translation 'my-snat-translation'
100 bigip_snat_translation:
101 name: my-snat-pool
102 state: present
103 address: 10.10.10.10
104 provider:
105 server: lb.mydomain.com
106 user: admin
107 password: secret
108 delegate_to: localhost
109
110 - name: Modify a SNAT translation 'my-snat-translation'
111 bigip_snat_translation:
112 name: my-snat-pool
113 state: present
114 address: 10.10.10.10
115 arp: false
116 connection_limit: 300
117 ip_idle_timeout: 1800
118 tcp_idle_timeout: 1800
119 udp_idle_timeout: 1800
120 provider:
121 server: lb.mydomain.com
122 user: admin
123 password: secret
124 delegate_to: localhost
125
126 - name: Disable a SNAT translation 'my-snat-translation'
127 bigip_snat_translation:
128 name: my-snat-pool
129 state: disabled
130 address: 10.10.10.10
131 arp: false
132 connection_limit: 300
133 ip_idle_timeout: 1800
134 tcp_idle_timeout: 1800
135 udp_idle_timeout: 1800
136 provider:
137 server: lb.mydomain.com
138 user: admin
139 password: secret
140 delegate_to: localhost
141
142 - name: Enable a SNAT translation 'my-snat-translation'
143 bigip_snat_translation:
144 name: my-snat-pool
145 state: enabled
146 address: 10.10.10.10
147 arp: false
148 connection_limit: 300
149 ip_idle_timeout: 1800
150 tcp_idle_timeout: 1800
151 udp_idle_timeout: 1800
152 provider:
153 server: lb.mydomain.com
154 user: admin
155 password: secret
156 delegate_to: localhost
157
158 - name: Create using partition other then /Common on a SNAT translation 'my-new-snat-translation'
159 bigip_snat_translation:
160 name: my-new-snat-pool
161 state: enabled
162 address: 10.10.10.10
163 arp: false
164 connection_limit: 300
165 ip_idle_timeout: 1800
166 partition: ansible
167 tcp_idle_timeout: 1800
168 udp_idle_timeout: 1800
169 provider:
170 server: lb.mydomain.com
171 user: admin
172 password: secret
173 delegate_to: localhost
174
175 - name: Modify using traffic group other then /Common/traffic-group-1 on a SNAT translation 'my-new-snat-translation'
176 bigip_snat_translation:
177 name: my-new-snat-pool
178 state: enabled
179 address: 10.10.10.10
180 arp: false
181 connection_limit: 300
182 ip_idle_timeout: 1800
183 partition: ansible
184 tcp_idle_timeout: 1800
185 traffic_group: /Common/ansible
186 udp_idle_timeout: 1800
187 provider:
188 server: lb.mydomain.com
189 user: admin
190 password: secret
191 delegate_to: localhost
192 '''
193
194 RETURN = r'''
195 address:
196 description:
197 - IP address used for SNAT translation.
198 returned: changed and success
199 type: str
200 sample: "10.10.10.10"
201 arp:
202 description: Whether snat-translation sends arp requests.
203 returned: changed
204 type: bool
205 sample: true
206 connection_limit:
207 description: The new connection limit of the virtual address.
208 returned: changed
209 type: int
210 sample: 1000
211 description:
212 description: Description of the snat-translation.
213 returned: changed
214 type: str
215 sample: My snat-translation
216 ip_idle_timeout:
217 description: IP idle timeout value for the snat-translation.
218 returned: changed
219 type: str
220 sample: 300
221 state:
222 description: The new state of the snat-translation.
223 returned: changed
224 type: str
225 sample: disabled
226 tcp_idle_timeout:
227 description: TCP idle timeout value for the snat-translation.
228 returned: changed
229 type: str
230 sample: 1800
231 traffic_group:
232 description: Assigned traffic group.
233 returned: changed
234 type: str
235 sample: /Common/traffic-group-1
236 udp_idle_timeout:
237 description: UDP idle timeout value for the snat-translation.
238 returned: changed
239 type: str
240 sample: indefinite
241 '''
242 from datetime import datetime
243
244 from ansible.module_utils.basic import (
245 AnsibleModule, env_fallback
246 )
247
248 from ..module_utils.bigip import F5RestClient
249 from ..module_utils.common import (
250 F5ModuleError, AnsibleF5Parameters, transform_name, f5_argument_spec, flatten_boolean, fq_name
251 )
252 from ..module_utils.compare import cmp_str_with_none
253 from ..module_utils.ipaddress import (
254 is_valid_ip, compress_address
255 )
256 from ..module_utils.icontrol import tmos_version
257 from ..module_utils.teem import send_teem
258
259
260 class Parameters(AnsibleF5Parameters):
261 api_map = {
262 'connectionLimit': 'connection_limit',
263 'ipIdleTimeout': 'ip_idle_timeout',
264 'tcpIdleTimeout': 'tcp_idle_timeout',
265 'trafficGroup': 'traffic_group',
266 'udpIdleTimeout': 'udp_idle_timeout',
267 }
268
269 api_attributes = [
270 'address',
271 'arp',
272 'connectionLimit',
273 'description',
274 'disabled',
275 'enabled',
276 'ipIdleTimeout',
277 'tcpIdleTimeout',
278 'trafficGroup',
279 'udpIdleTimeout',
280 ]
281
282 returnables = [
283 'address',
284 'arp',
285 'connection_limit',
286 'description',
287 'disabled',
288 'enabled',
289 'ip_idle_timeout',
290 'state',
291 'tcp_idle_timeout',
292 'traffic_group',
293 'udp_idle_timeout',
294 ]
295
296 updatables = [
297 'arp',
298 'connection_limit',
299 'description',
300 'disabled',
301 'enabled',
302 'ip_idle_timeout',
303 'traffic_group',
304 'tcp_idle_timeout',
305 'udp_idle_timeout',
306 ]
307
308
309 class ApiParameters(Parameters):
310 @property
311 def connection_limit(self):
312 if self._values['connection_limit'] is None:
313 return None
314 return int(self._values['connection_limit'])
315
316 @property
317 def enabled(self):
318 if 'enabled' in self._values:
319 return True
320 return False
321
322 @property
323 def disabled(self):
324 if 'disabled' in self._values:
325 return True
326 return False
327
328
329 class ModuleParameters(Parameters):
330
331 def _validate_timeout_limit(self, limit):
332 if limit is None:
333 return None
334 if limit in ['indefinite', '4294967295']:
335 return 'indefinite'
336 if 0 <= int(limit) <= 4294967295:
337 return str(limit)
338 raise F5ModuleError(
339 "Valid 'maximum_age' must be in range 0 - 4294967295, or 'indefinite'."
340 )
341
342 def _validate_conn_limit(self, limit):
343 if limit is None:
344 return None
345 if 0 <= int(limit) <= 65535:
346 return int(limit)
347 raise F5ModuleError(
348 "Valid 'connection_limit' must be in range 0 - 65535."
349 )
350
351 @property
352 def address(self):
353 if self._values['address'] is None:
354 return None
355 if len(self._values['address'].split('%')) > 1:
356 address, rd = self._values['address'].split('%')
357 if is_valid_ip(address):
358 result = '{0}%{1}'.format(compress_address(address), rd)
359 return result
360 else:
361 if is_valid_ip(self._values['address']):
362 return self._values['address']
363 raise F5ModuleError(
364 "The provided address: {0} is not a valid IP address".format(self._values['address'])
365 )
366
367 @property
368 def arp(self):
369 result = flatten_boolean(self._values['arp'])
370 if result is None:
371 return None
372 if result == 'yes':
373 return 'enabled'
374 return 'disabled'
375
376 @property
377 def connection_limit(self):
378 if self._values['connection_limit'] is None:
379 return None
380 return int(self._validate_conn_limit(self._values['connection_limit']))
381
382 @property
383 def description(self):
384 if self._values['description'] is None:
385 return None
386 if self._values['description'] in ['', 'none']:
387 return ''
388 return self._values['description']
389
390 @property
391 def disabled(self):
392 if self._values['state'] == 'disabled':
393 return True
394
395 @property
396 def enabled(self):
397 if self._values['state'] in ['enabled', 'present']:
398 return True
399
400 @property
401 def ip_idle_timeout(self):
402 return self._validate_timeout_limit(self._values['ip_idle_timeout'])
403
404 @property
405 def state(self):
406 if self.enabled is True and self._values['state'] != 'present':
407 return 'enabled'
408 elif self.disabled is True:
409 return 'disabled'
410 else:
411 return self._values['state']
412
413 @property
414 def tcp_idle_timeout(self):
415 return self._validate_timeout_limit(self._values['tcp_idle_timeout'])
416
417 @property
418 def traffic_group(self):
419 if self._values['traffic_group'] is None:
420 return None
421 return fq_name(self.partition, self._values['traffic_group'])
422
423 @property
424 def udp_idle_timeout(self):
425 return self._validate_timeout_limit(self._values['udp_idle_timeout'])
426
427
428 class Changes(Parameters):
429 def to_return(self):
430 result = {}
431 try:
432 for returnable in self.returnables:
433 result[returnable] = getattr(self, returnable)
434 result = self._filter_params(result)
435 except Exception:
436 pass
437 return result
438
439
440 class UsableChanges(Changes):
441 pass
442
443
444 class ReportableChanges(Changes):
445 def _change_limit_value(self, value):
446 if value == 4294967295:
447 return 'indefinite'
448 else:
449 return value
450
451 @property
452 def arp(self):
453 return flatten_boolean(self._values['arp'])
454
455 @property
456 def ip_idle_timeout(self):
457 if self._values['ip_idle_timeout'] is None:
458 return None
459 return self._change_limit_value(self._values['ip_idle_timeout'])
460
461 @property
462 def tcp_idle_timeout(self):
463 if self._values['tcp_idle_timeout'] is None:
464 return None
465 return self._change_limit_value(self._values['tcp_idle_timeout'])
466
467 @property
468 def udp_idle_timeout(self):
469 if self._values['udp_idle_timeout'] is None:
470 return None
471 return self._change_limit_value(self._values['udp_idle_timeout'])
472
473
474 class Difference(object):
475 def __init__(self, want, have=None):
476 self.want = want
477 self.have = have
478
479 def compare(self, param):
480 try:
481 result = getattr(self, param)
482 return result
483 except AttributeError:
484 return self.__default(param)
485
486 def __default(self, param):
487 attr1 = getattr(self.want, param)
488 try:
489 attr2 = getattr(self.have, param)
490 if attr1 != attr2:
491 return attr1
492 except AttributeError:
493 return attr1
494
495 @property
496 def description(self):
497 return cmp_str_with_none(self.want.description, self.have.description)
498
499
500 class ModuleManager(object):
501 def __init__(self, *args, **kwargs):
502 self.module = kwargs.get('module', None)
503 self.client = F5RestClient(**self.module.params)
504 self.want = ModuleParameters(params=self.module.params)
505 self.have = ApiParameters()
506 self.changes = UsableChanges()
507
508 def _announce_deprecations(self, result):
509 warnings = result.pop('__warnings', [])
510 for warning in warnings:
511 self.module.deprecate(
512 msg=warning['msg'],
513 version=warning['version']
514 )
515
516 def _set_changed_options(self):
517 changed = {}
518 for key in Parameters.returnables:
519 if getattr(self.want, key) is not None:
520 changed[key] = getattr(self.want, key)
521 if changed:
522 self.changes = UsableChanges(params=changed)
523
524 def _update_changed_options(self):
525 diff = Difference(self.want, self.have)
526 updatables = Parameters.updatables
527 changed = dict()
528 for k in updatables:
529 change = diff.compare(k)
530 if change is None:
531 continue
532 else:
533 if isinstance(change, dict):
534 changed.update(change)
535 else:
536 changed[k] = change
537 if changed:
538 self.changes = UsableChanges(params=changed)
539 return True
540 return False
541
542 def exec_module(self):
543 start = datetime.now().isoformat()
544 version = tmos_version(self.client)
545 changed = False
546 result = dict()
547 state = self.want.state
548
549 if state in ['present', 'enabled', 'disabled']:
550 changed = self.present()
551 elif state == "absent":
552 changed = self.absent()
553
554 reportable = ReportableChanges(params=self.changes.to_return())
555 changes = reportable.to_return()
556 result.update(**changes)
557
558 if self.module._diff and self.have:
559 result['diff'] = self.make_diff()
560
561 result.update(dict(changed=changed))
562 self._announce_deprecations(result)
563 send_teem(start, self.client, self.module, version)
564 return result
565
566 def _grab_attr(self, item):
567 result = dict()
568 updatables = Parameters.updatables
569 for k in updatables:
570 if getattr(item, k) is not None:
571 result[k] = getattr(item, k)
572 return result
573
574 def make_diff(self):
575 result = dict(before=self._grab_attr(self.have), after=self._grab_attr(self.want))
576 return result
577
578 def present(self):
579 if self.exists():
580 return self.update()
581 else:
582 return self.create()
583
584 def absent(self):
585 changed = False
586 if self.exists():
587 changed = self.remove()
588 return changed
589
590 def should_update(self):
591 result = self._update_changed_options()
592 if result:
593 return True
594 return False
595
596 def update(self):
597 self.have = self.read_current_from_device()
598 if not self.should_update():
599 return False
600 if self.module.check_mode:
601 return True
602 self.update_on_device()
603 return True
604
605 def create(self):
606 self._set_changed_options()
607 if self.module.check_mode:
608 return True
609 self.create_on_device()
610 if not self.exists():
611 raise F5ModuleError("Failed to create the SNAT pool")
612 return True
613
614 def remove(self):
615 if self.module.check_mode:
616 return True
617 self.remove_from_device()
618 if self.exists():
619 raise F5ModuleError("Failed to delete the SNAT pool")
620 return True
621
622 def exists(self):
623 uri = "https://{0}:{1}/mgmt/tm/ltm/snat-translation/{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 resp.status == 404 or 'code' in response and response['code'] == 404:
635 return False
636 if resp.status in [200, 201] or 'code' in response and response['code'] in [200, 201]:
637 return True
638
639 errors = [401, 403, 409, 500, 501, 502, 503, 504]
640
641 if resp.status in errors or 'code' in response and response['code'] in errors:
642 if 'message' in response:
643 raise F5ModuleError(response['message'])
644 else:
645 raise F5ModuleError(resp.content)
646
647 def create_on_device(self):
648 params = self.changes.api_params()
649 params['name'] = self.want.name
650 params['partition'] = self.want.partition
651 uri = "https://{0}:{1}/mgmt/tm/ltm/snat-translation/".format(
652 self.client.provider['server'],
653 self.client.provider['server_port']
654 )
655 resp = self.client.api.post(uri, json=params)
656 try:
657 response = resp.json()
658 except ValueError as ex:
659 raise F5ModuleError(str(ex))
660
661 if 'code' in response and response['code'] in [400, 409]:
662 if 'message' in response:
663 raise F5ModuleError(response['message'])
664 else:
665 raise F5ModuleError(resp.content)
666 return True
667
668 def update_on_device(self):
669 params = self.changes.api_params()
670 uri = "https://{0}:{1}/mgmt/tm/ltm/snat-translation/{2}".format(
671 self.client.provider['server'],
672 self.client.provider['server_port'],
673 transform_name(self.want.partition, self.want.name)
674 )
675 resp = self.client.api.patch(uri, json=params)
676 try:
677 response = resp.json()
678 except ValueError as ex:
679 raise F5ModuleError(str(ex))
680
681 if 'code' in response and response['code'] == 400:
682 if 'message' in response:
683 raise F5ModuleError(response['message'])
684 else:
685 raise F5ModuleError(resp.content)
686
687 def remove_from_device(self):
688 uri = "https://{0}:{1}/mgmt/tm/ltm/snat-translation/{2}".format(
689 self.client.provider['server'],
690 self.client.provider['server_port'],
691 transform_name(self.want.partition, self.want.name)
692 )
693 response = self.client.api.delete(uri)
694 if response.status == 200:
695 return True
696 raise F5ModuleError(response.content)
697
698 def read_current_from_device(self):
699 uri = "https://{0}:{1}/mgmt/tm/ltm/snat-translation/{2}".format(
700 self.client.provider['server'],
701 self.client.provider['server_port'],
702 transform_name(self.want.partition, self.want.name)
703 )
704 resp = self.client.api.get(uri)
705 try:
706 response = resp.json()
707 except ValueError as ex:
708 raise F5ModuleError(str(ex))
709
710 if 'code' in response and response['code'] == 400:
711 if 'message' in response:
712 raise F5ModuleError(response['message'])
713 else:
714 raise F5ModuleError(resp.content)
715 return ApiParameters(params=response)
716
717
718 class ArgumentSpec(object):
719 def __init__(self):
720 self.supports_check_mode = True
721 argument_spec = dict(
722 address=dict(
723 aliases=['ip']
724 ),
725 arp=dict(
726 type='bool'
727 ),
728 connection_limit=dict(
729 type='int'
730 ),
731 description=dict(),
732 ip_idle_timeout=dict(),
733 name=dict(required=True),
734 partition=dict(
735 fallback=(env_fallback, ['F5_PARTITION'])
736 ),
737 state=dict(
738 default='present',
739 choices=['absent', 'present', 'enabled', 'disabled']
740 ),
741 tcp_idle_timeout=dict(),
742 traffic_group=dict(),
743 udp_idle_timeout=dict()
744 )
745 self.argument_spec = {}
746 self.argument_spec.update(f5_argument_spec)
747 self.argument_spec.update(argument_spec)
748 self.required_if = [
749 ['state', 'present', ['address', 'name']],
750 ['state', 'enabled', ['address', 'name']],
751 ['state', 'disabled', ['address', 'name']],
752 ]
753
754
755 def main():
756 spec = ArgumentSpec()
757
758 module = AnsibleModule(
759 argument_spec=spec.argument_spec,
760 supports_check_mode=spec.supports_check_mode,
761 required_if=spec.required_if
762 )
763
764 try:
765 mm = ModuleManager(module=module)
766 results = mm.exec_module()
767 module.exit_json(**results)
768 except F5ModuleError as ex:
769 module.fail_json(msg=str(ex))
770
771
772 if __name__ == '__main__':
773 main()