Debian Codegraph @

ansible_collections/f5networks/f5_modules/plugins/modules/bigip_apm_acl.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_apm_acl
13 short_description: Manage user-defined APM ACLs
14 description:
15 - Manage user-defined APM ACLs.
16 version_added: "1.0.0"
17 options:
18 name:
19 description:
20 - Specifies the name of the ACL to manage.
21 type: str
22 required: True
23 description:
24 description:
25 - User created ACL description.
26 type: str
27 type:
28 description:
29 - Specifies the type of ACL to create.
30 - Once the type is set it cannot be changed.
31 type: str
32 choices:
33 - static
34 - dynamic
35 acl_order:
36 description:
37 - Specifies a number that indicates the order of this ACL relative to other ACLs.
38 - When not set, the device will always place the ACL after the last one created.
39 - The lower the number, the higher the ACL will be in the general order, with the lowest number C(0) being the topmost one.
40 - Valid range of values is between C(0) and C(65535) inclusive.
41 type: int
42 path_match_case:
43 description:
44 - Specifies whether alphabetic case is considered when matching paths in an access control entry.
45 type: bool
46 entries:
47 description:
48 - Access control entries that define the ACL matching and its respective behavior.
49 - The order in which the rules are placed as arguments to this parameter determines their order in the ACL,
50 in other words changing the order of the same elements will cause a change on the unit.
51 - Changes in the number of rules will always trigger device change. This means user input will take
52 precedence over what is on device.
53 type: list
54 elements: dict
55 suboptions:
56 action:
57 description:
58 - Specifies the action that the access control entry takes when a match for this access control entry
59 is encountered.
60 type: str
61 required: True
62 choices:
63 - allow
64 - reject
65 - discard
66 - continue
67 dst_port:
68 description:
69 - Specifies the destination port for the access control entry.
70 - Can be set to C(*) to indicate all ports.
71 - Parameter is mutually exclusive with C(dst_port_range).
72 type: str
73 dst_port_range:
74 description:
75 - Specifies the destination port range for the access control entry.
76 - Parameter is mutually exclusive with C(dst_port_range).
77 - To indicate all ports the C(dst_port) parameter must be used and set to C(*).
78 type: str
79 src_port:
80 description:
81 - Specifies the source port for the access control entry.
82 - Can be set to C(*) to indicate all ports.
83 - Parameter is mutually exclusive with C(src_port_range).
84 type: str
85 src_port_range:
86 description:
87 - Specifies the source port range for the access control entry.
88 - Parameter is mutually exclusive with C(src_port_range).
89 - To indicate all ports the C(src_port) parameter must be used and set to C(*).
90 type: str
91 dst_addr:
92 description:
93 - Specifies the destination IP address for the access control entry.
94 - When set to C(any) the ACL will match any destination address, C(dst_mask) is ignored in this case.
95 type: str
96 dst_mask:
97 description:
98 - Optional parameter that specifies the destination network mask for the access control entry.
99 - If not specified and C(dst_addr) is not C(any), the C(dst_addr) is deemed to be host address.
100 type: str
101 src_addr:
102 description:
103 - Specifies the source IP address for the access control entry.
104 - When set to C(any) the ACL will match any source address, C(src_mask) is ignored in this case.
105 type: str
106 src_mask:
107 description:
108 - Optional parameter that specifies the source network mask for the access control entry.
109 - If not specified and C(src_addr) is not C(any), the C(src_addr) is deemed to be host address.
110 type: str
111 scheme:
112 description:
113 - This parameter applies to Layer 7 access control entries only.
114 - "Specifies the URI scheme: C(http), C(https) or C(any) on which the access control entry operates."
115 type: str
116 choices:
117 - http
118 - https
119 - any
120 protocol:
121 description:
122 - This parameter applies to Layer 4 access control entries only.
123 - "Specifies the protocol: C(tcp), C(udp), C(icmp) or C(all) protocols,
124 to which the access control entry applies."
125 type: str
126 choices:
127 - tcp
128 - icmp
129 - udp
130 - all
131 host_name:
132 description:
133 - This parameter applies to Layer 7 access control entries only.
134 - Specifies a host to which the access control entry applies.
135 type: str
136 paths:
137 description:
138 - This parameter applies to Layer 7 access control entries only.
139 - Specifies the path or paths to which the access control entry applies.
140 type: str
141 log:
142 description:
143 - Specifies the log level that is logged when actions of this type occur.
144 - When C(none) it will log nothing, which is a default action.
145 - When C(packet) it will log the matched packet.
146 type: str
147 choices:
148 - none
149 - packet
150 partition:
151 description:
152 - Device partition to manage resources on.
153 type: str
154 default: Common
155 state:
156 description:
157 - When C(state) is C(present), ensures that the ACL exists.
158 - When C(state) is C(absent), ensures that the ACL is removed.
159 type: str
160 choices:
161 - present
162 - absent
163 default: present
164 extends_documentation_fragment: f5networks.f5_modules.f5
165 author:
166 - Wojciech Wypior (@wojtek0806)
167 '''
168
169 EXAMPLES = r'''
170 - name: Create a static ACL with L4 entries
171 bigip_apm_acl:
172 name: L4foo
173 acl_order: 0
174 type: static
175 entries:
176 - action: allow
177 dst_port: '80'
178 dst_addr: '192.168.1.1'
179 src_port: '443'
180 src_addr: '10.10.10.0'
181 src_mask: '255.255.255.128'
182 protocol: tcp
183 - action: reject
184 dst_port: '*'
185 dst_addr: '192.168.1.1'
186 src_port: '*'
187 src_addr: '10.10.10.0'
188 src_mask: '255.255.255.128'
189 protocol: tcp
190 log: packet
191 provider:
192 password: secret
193 server: lb.mydomain.com
194 user: admin
195 delegate_to: localhost
196
197 - name: Create a static ACL with L7 entries
198 bigip_apm_acl:
199 name: L7foo
200 acl_order: 1
201 type: static
202 path_match_case: false
203 entries:
204 - action: allow
205 host_name: 'foobar.com'
206 paths: '/shopfront'
207 scheme: https
208 - action: reject
209 host_name: 'internal_foobar.com'
210 paths: '/admin'
211 scheme: any
212 log: packet
213 provider:
214 password: secret
215 server: lb.mydomain.com
216 user: admin
217 delegate_to: localhost
218
219 - name: Create a static ACL with L7/L4 entries
220 bigip_apm_acl:
221 name: L7L4foo
222 acl_order: 2
223 type: static
224 path_match_case: false
225 entries:
226 - action: allow
227 host_name: 'foobar.com'
228 paths: '/shopfront'
229 scheme: https
230 dst_port: '8181'
231 dst_addr: '192.168.1.1'
232 protocol: tcp
233 - action: reject
234 dst_addr: '192.168.1.1'
235 host_name: 'internal_foobar.com'
236 paths: '/admin'
237 scheme: any
238 protocol: all
239 log: packet
240 provider:
241 password: secret
242 server: lb.mydomain.com
243 user: admin
244 delegate_to: localhost
245
246 - name: Modify a static ACL entries
247 bigip_apm_acl:
248 name: L4foo
249 entries:
250 - action: allow
251 dst_port: '80'
252 dst_addr: '192.168.1.1'
253 src_port: '443'
254 src_addr: '10.10.10.0'
255 src_mask: '255.255.255.128'
256 protocol: tcp
257 - action: discard
258 dst_port: '*'
259 dst_addr: 192.168.1.1
260 src_port: '*'
261 src_addr: '10.10.10.0'
262 src_mask: '255.2155.255.128'
263 protocol: all
264 provider:
265 password: secret
266 server: lb.mydomain.com
267 user: admin
268 delegate_to: localhost
269
270 - name: Remove static ACL
271 bigip_apm_acl:
272 name: L4foo
273 state: absent
274 provider:
275 password: secret
276 server: lb.mydomain.com
277 user: admin
278 delegate_to: localhost
279 '''
280
281 RETURN = r'''
282 description:
283 description: The new description of the ACL.
284 returned: changed
285 type: str
286 sample: My ACL
287 type:
288 description: The type of ACL to create.
289 returned: changed
290 type: str
291 sample: static
292 acl_order:
293 description: The order of this ACL relative to other ACLs.
294 returned: changed
295 type: int
296 sample: 10
297 path_match_case:
298 description: Specifies whether alphabetic case is considered when matching paths in an access control entry.
299 returned: changed
300 type: bool
301 sample: true
302 entries:
303 description: Access control entries that define the ACL matching and its respective behavior.
304 type: complex
305 returned: changed
306 contains:
307 action:
308 description: Action the access control entry takes when a match for this access control entry is encountered.
309 returned: changed
310 type: str
311 sample: allow
312 dst_port:
313 description: The destination port for the access control entry.
314 returned: changed
315 type: str
316 sample: '80'
317 dst_port_range:
318 description: The destination port range for the access control entry.
319 returned: changed
320 type: str
321 sample: '80-81'
322 src_port:
323 description: The source port for the access control entry.
324 returned: changed
325 type: str
326 sample: '80'
327 src_port_range:
328 description: The source port range for the access control entry.
329 returned: changed
330 type: str
331 sample: '80-81'
332 dst_addr:
333 description: The destination IP address for the access control entry.
334 returned: changed
335 type: str
336 sample: 192.168.0.1
337 dst_mask:
338 description: The destination network mask for the access control entry.
339 returned: changed
340 type: str
341 sample: 255.255.255.128
342 src_addr:
343 description: The source IP address for the access control entry.
344 returned: changed
345 type: str
346 sample: 192.168.0.1
347 src_mask:
348 description: The source network mask for the access control entry.
349 returned: changed
350 type: str
351 sample: 255.255.255.128
352 scheme:
353 description: The URI scheme on which the access control entry operates.
354 returned: changed
355 type: str
356 sample: https
357 protocol:
358 description: The protocol to which the access control entry applies.
359 returned: changed
360 type: str
361 sample: tcp
362 host_name:
363 description: The host to which the access control entry applies.
364 returned: changed
365 type: str
366 sample: foobar.com
367 paths:
368 description: The path or paths to which the access control entry applies.
369 returned: changed
370 type: str
371 sample: /fooshop
372 log:
373 description: The log level that is logged when actions of this type occur.
374 returned: changed
375 type: str
376 sample: packet
377 sample: hash/dictionary of values
378 '''
379 from datetime import datetime
380
381 from ansible.module_utils.basic import (
382 AnsibleModule, env_fallback
383 )
384 from ipaddress import (
385 ip_network, ip_interface
386 )
387
388 from ..module_utils.bigip import F5RestClient
389 from ..module_utils.common import (
390 F5ModuleError, AnsibleF5Parameters, transform_name, f5_argument_spec, flatten_boolean
391 )
392 from ..module_utils.compare import cmp_str_with_none
393 from ..module_utils.icontrol import (
394 module_provisioned, tmos_version
395 )
396 from ..module_utils.ipaddress import (
397 is_valid_ip, is_valid_ip_network
398 )
399 from ..module_utils.teem import send_teem
400
401
402 class Parameters(AnsibleF5Parameters):
403 api_map = {
404 'aclOrder': 'acl_order',
405 'pathMatchCase': 'path_match_case'
406 }
407
408 api_attributes = [
409 'entries',
410 'description',
411 'aclOrder',
412 'pathMatchCase',
413 'type',
414 ]
415
416 returnables = [
417 'entries',
418 'acl_order',
419 'path_match_case',
420 'type',
421 'description',
422 ]
423
424 updatables = [
425 'entries',
426 'acl_order',
427 'path_match_case',
428 'type',
429 'description',
430 ]
431
432
433 class ApiParameters(Parameters):
434 pass
435
436
437 class ModuleParameters(Parameters):
438 protocol_map = {
439 'icmp': 1,
440 'tcp': 6,
441 'udp': 17,
442 'all': 0
443 }
444
445 @property
446 def path_match_case(self):
447 result = flatten_boolean(self._values['path_match_case'])
448 if result == 'yes':
449 return 'true'
450 if result == 'no':
451 return 'false'
452
453 @property
454 def acl_order(self):
455 if self._values['acl_order'] is None:
456 return None
457 if 0 < self._values['acl_order'] > 65535:
458 raise F5ModuleError(
459 "Specified number is out of valid range, correct range is between 0 and 65535."
460 )
461 return self._values['acl_order']
462
463 @property
464 def description(self):
465 if self._values['description'] is None:
466 return None
467 elif self._values['description'] in ['none', '']:
468 return ''
469 return self._values['description']
470
471 @property
472 def entries(self):
473 if self._values['entries'] is None:
474 return None
475 if self._values['entries'] == 'none':
476 return []
477 result = []
478 for x in self._values['entries']:
479 element = dict()
480 element['action'] = x['action']
481 if 'dst_port' in x and x['dst_port'] is not None:
482 if x['dst_port'] == '*':
483 element['dstEndPort'] = 0
484 element['dstStartPort'] = 0
485 else:
486 self._validate_port(int(x['dst_port']))
487 element['dstEndPort'] = int(x['dst_port'])
488 element['dstStartPort'] = int(x['dst_port'])
489 if 'dst_port_range' in x and x['dst_port_range'] is not None:
490 start, stop = self._validate_ports(x['dst_port_range'])
491 element['dstEndPort'] = stop
492 element['dstStartPort'] = start
493 if 'src_port' in x and x['src_port'] is not None:
494 if x['src_port'] == '*':
495 element['srcEndPort'] = 0
496 element['srcStartPort'] = 0
497 else:
498 self._validate_port(int(x['src_port']))
499 element['srcEndPort'] = int(x['src_port'])
500 element['srcStartPort'] = int(x['src_port'])
501 if 'src_port_range' in x and x['src_port_range'] is not None:
502 start, stop = self._validate_ports(x['src_port_range'])
503 element['srcEndPort'] = stop
504 element['srcStartPort'] = start
505 if 'dst_addr' in x and x['dst_addr'] is not None:
506 if 'dst_mask' in x and x['dst_mask'] is not None:
507 element['dstSubnet'] = self._convert_address(x['dst_addr'], x['dst_mask'])
508 else:
509 element['dstSubnet'] = self._convert_address(x['dst_addr'])
510 if 'src_addr' in x and x['src_addr'] is not None:
511 if 'src_mask' in x and x['src_mask'] is not None:
512 element['srcSubnet'] = self._convert_address(x['src_addr'], x['src_mask'])
513 else:
514 element['srcSubnet'] = self._convert_address(x['src_addr'])
515 if 'scheme' in x and x['scheme'] is not None:
516 element['scheme'] = x['scheme']
517 if 'protocol' in x and x['protocol'] is not None:
518 element['protocol'] = self.protocol_map[x['protocol']]
519 if 'host_name' in x and x['host_name'] is not None:
520 element['host'] = x['host_name']
521 if 'paths' in x and x['paths'] is not None:
522 element['paths'] = x['paths']
523 if 'log' in x and x['log'] is not None:
524 element['log'] = x['log']
525 result.append(element)
526 return result
527
528 def _validate_port(self, item):
529 if 0 < item > 65535:
530 raise F5ModuleError(
531 "Specified port number is out of valid range, correct range is between 0 and 65535."
532 )
533
534 def _validate_ports(self, item):
535 start, stop = item.split('-')
536 start = int(start.strip())
537 stop = int(stop.strip())
538 if 0 < start > 65535 or 0 < stop > 65535:
539 raise F5ModuleError(
540 "Specified port number is out of valid range, correct range is between 0 and 65535."
541 )
542 return start, stop
543
544 def _convert_address(self, item, mask=None):
545 if item == 'any':
546 return '0.0.0.0/0'
547 if not is_valid_ip(item):
548 raise F5ModuleError('The provided IP address is not a valid IP address.')
549 if mask:
550 msk = self._convert_netmask(mask)
551 network = '{0}/{1}'.format(item, msk)
552 if is_valid_ip_network(u'{0}'.format(network)):
553 return network
554 else:
555 raise F5ModuleError(
556 'The provided IP and Mask are not a valid IP network.'
557 )
558 host = ip_interface(u'{0}'.format(item))
559 return host.with_prefixlen
560
561 def _convert_netmask(self, item):
562 result = -1
563 try:
564 result = int(item)
565 if 0 < result < 256:
566 pass
567 except ValueError:
568 if is_valid_ip(item):
569 ip = ip_network(u'0.0.0.0/%s' % str(item))
570 result = ip.prefixlen
571 if result < 0:
572 raise F5ModuleError(
573 'The provided netmask {0} is neither in IP or CIDR format'.format(result)
574 )
575 return result
576
577
578 class Changes(Parameters):
579 def to_return(self):
580 result = {}
581 try:
582 for returnable in self.returnables:
583 result[returnable] = getattr(self, returnable)
584 result = self._filter_params(result)
585 except Exception:
586 raise
587 return result
588
589
590 class UsableChanges(Changes):
591 pass
592
593
594 class ReportableChanges(Changes):
595 protocol_map = {
596 1: 'icmp',
597 6: 'tcp',
598 17: 'udp',
599 0: 'all'
600 }
601
602 @property
603 def path_match_case(self):
604 result = flatten_boolean(self._values['path_match_case'])
605 return result
606
607 @property
608 def entries(self):
609 if self._values['entries'] is None:
610 return None
611 if not self._values['entries']:
612 return 'none'
613 result = []
614 for x in self._values['entries']:
615 to_filter = dict()
616 to_filter['action'] = x['action']
617 if 'dstStartPort' in x and 'dstEndPort' in x:
618 if x['dstStartPort'] == x['dstEndPort']:
619 if x['dstStartPort'] == 0:
620 to_filter['dst_port'] = '*'
621 else:
622 to_filter['dst_port'] = str(x['dstStartPort'])
623 else:
624 to_filter['dst_port_range'] = '{0}-{1}'.format(x['dstStartPort'], x['dstEndPort'])
625 if 'srcStartPort' in x and 'srcEndPort' in x:
626 if x['srcStartPort'] == x['srcEndPort']:
627 if x['srcStartPort'] == 0:
628 to_filter['src_port'] = '*'
629 else:
630 to_filter['src_port'] = str(x['srcStartPort'])
631 else:
632 to_filter['src_port_range'] = '{0}-{1}'.format(x['srcStartPort'], x['srcEndPort'])
633 if 'dstSubnet' in x:
634 to_filter['dst_addr'], to_filter['dst_mask'] = self._convert_address(x['dstSubnet'])
635 if 'srcSubnet' in x:
636 to_filter['src_addr'], to_filter['src_mask'] = self._convert_address(x['srcSubnet'])
637 if 'scheme' in x:
638 to_filter['scheme'] = x['scheme']
639 if 'protocol' in x:
640 to_filter['protocol'] = self.protocol_map[x['protocol']]
641 if 'host' in x:
642 to_filter['host_name'] = x['host']
643 if 'paths' in x:
644 to_filter['paths'] = x['paths']
645 if 'log' in x:
646 to_filter['log'] = x['log']
647 element = self._filter_params(to_filter)
648 result.append(element)
649 return result
650
651 def _convert_address(self, item):
652 if item == '0.0.0.0/0':
653 return 'any', None
654 result = ip_network(u'{0}'.format(item))
655 if result.prefixlen == 32:
656 return str(result.network_address), None
657 else:
658 return str(result.network_address), str(result.netmask)
659
660
661 class Difference(object):
662 def __init__(self, want, have=None):
663 self.want = want
664 self.have = have
665
666 def compare(self, param):
667 try:
668 result = getattr(self, param)
669 return result
670 except AttributeError:
671 return self.__default(param)
672
673 def __default(self, param):
674 attr1 = getattr(self.want, param)
675 try:
676 attr2 = getattr(self.have, param)
677 if attr1 != attr2:
678 return attr1
679 except AttributeError:
680 return attr1
681
682 @property
683 def description(self):
684 return cmp_str_with_none(self.want.description, self.have.description)
685
686 @property
687 def entries(self):
688 if self.want.entries is None:
689 return None
690 if self.have.entries is None and self.want.entries == []:
691 return None
692
693 want = self.want.entries
694 have = list()
695 # First we compare if both lists are equal, if want is bigger or smaller than have, we assume user change
696 if len(self.want.entries) > len(self.have.entries) or len(self.want.entries) < len(self.have.entries):
697 return self.want.entries
698
699 # If lists are equal then we compare items to verify change was made
700
701 # First we remove extra keys in have
702 for idx, item in enumerate(want):
703 entry = self._filter_have(item, self.have.entries[idx])
704 have.append(entry)
705 # Compare each element in the list by position
706 for idx, item in enumerate(want):
707 if item != have[idx]:
708 return self.want.entries
709
710 def _filter_have(self, want, have):
711 to_check = set(want.keys()).intersection(set(have.keys()))
712 result = dict()
713 for k in list(to_check):
714 result[k] = have[k]
715 return result
716
717 @property
718 def type(self):
719 if self.want.type is None:
720 return None
721 if self.want.type == self.have.type:
722 return None
723 raise F5ModuleError(
724 "ACL type cannot be changed after ACL creation."
725 )
726
727
728 class ModuleManager(object):
729 def __init__(self, *args, **kwargs):
730 self.module = kwargs.get('module', None)
731 self.client = F5RestClient(**self.module.params)
732 self.want = ModuleParameters(params=self.module.params)
733 self.have = ApiParameters()
734 self.changes = UsableChanges()
735
736 def _set_changed_options(self):
737 changed = {}
738 for key in Parameters.returnables:
739 if getattr(self.want, key) is not None:
740 changed[key] = getattr(self.want, key)
741 if changed:
742 self.changes = UsableChanges(params=changed)
743
744 def _update_changed_options(self):
745 diff = Difference(self.want, self.have)
746 updatables = Parameters.updatables
747 changed = dict()
748 for k in updatables:
749 change = diff.compare(k)
750 if change is None:
751 continue
752 else:
753 if isinstance(change, dict):
754 changed.update(change)
755 else:
756 changed[k] = change
757 if changed:
758 self.changes = UsableChanges(params=changed)
759 return True
760 return False
761
762 def _announce_deprecations(self, result):
763 warnings = result.pop('__warnings', [])
764 for warning in warnings:
765 self.client.module.deprecate(
766 msg=warning['msg'],
767 version=warning['version']
768 )
769
770 def exec_module(self):
771 start = datetime.now().isoformat()
772 version = tmos_version(self.client)
773 if not module_provisioned(self.client, 'apm'):
774 raise F5ModuleError(
775 "APM must be provisioned to use this module."
776 )
777 changed = False
778 result = dict()
779 state = self.want.state
780
781 if state == "present":
782 changed = self.present()
783 elif state == "absent":
784 changed = self.absent()
785
786 reportable = ReportableChanges(params=self.changes.to_return())
787 changes = reportable.to_return()
788 result.update(**changes)
789 result.update(dict(changed=changed))
790 self._announce_deprecations(result)
791 send_teem(start, self.client, self.module, version)
792 return result
793
794 def present(self):
795 if self.exists():
796 return self.update()
797 else:
798 return self.create()
799
800 def absent(self):
801 if self.exists():
802 return self.remove()
803 return False
804
805 def should_update(self):
806 result = self._update_changed_options()
807 if result:
808 return True
809 return False
810
811 def update(self):
812 self.have = self.read_current_from_device()
813 if not self.should_update():
814 return False
815 if self.module.check_mode:
816 return True
817 self.update_on_device()
818 return True
819
820 def remove(self):
821 if self.module.check_mode:
822 return True
823 self.remove_from_device()
824 if self.exists():
825 raise F5ModuleError("Failed to delete the resource.")
826 return True
827
828 def create(self):
829 self._set_changed_options()
830 if self.module.check_mode:
831 return True
832 self.create_on_device()
833 return True
834
835 def exists(self):
836 errors = [401, 403, 409, 500, 501, 502, 503, 504]
837 uri = "https://{0}:{1}/mgmt/tm/apm/acl/{2}".format(
838 self.client.provider['server'],
839 self.client.provider['server_port'],
840 transform_name(self.want.partition, self.want.name)
841 )
842 resp = self.client.api.get(uri)
843 try:
844 response = resp.json()
845 except ValueError as ex:
846 raise F5ModuleError(str(ex))
847
848 if resp.status == 404 or 'code' in response and response['code'] == 404:
849 return False
850 if resp.status in [200, 201] or 'code' in response and response['code'] in [200, 201]:
851 return True
852
853 if resp.status in errors or 'code' in response and response['code'] in errors:
854 if 'message' in response:
855 raise F5ModuleError(response['message'])
856 else:
857 raise F5ModuleError(resp.content)
858
859 def create_on_device(self):
860 params = self.changes.api_params()
861 params['name'] = self.want.name
862 params['partition'] = self.want.partition
863 uri = "https://{0}:{1}/mgmt/tm/apm/acl/".format(
864 self.client.provider['server'],
865 self.client.provider['server_port'],
866 )
867 resp = self.client.api.post(uri, json=params)
868 try:
869 response = resp.json()
870 except ValueError as ex:
871 raise F5ModuleError(str(ex))
872
873 if resp.status in [200, 201] or 'code' in response and response['code'] in [200, 201]:
874 return True
875 raise F5ModuleError(resp.content)
876
877 def update_on_device(self):
878 params = self.changes.api_params()
879 uri = "https://{0}:{1}/mgmt/tm/apm/acl/{2}".format(
880 self.client.provider['server'],
881 self.client.provider['server_port'],
882 transform_name(self.want.partition, self.want.name)
883 )
884 resp = self.client.api.patch(uri, json=params)
885 try:
886 response = resp.json()
887 except ValueError as ex:
888 raise F5ModuleError(str(ex))
889
890 if resp.status in [200, 201] or 'code' in response and response['code'] in [200, 201]:
891 return True
892 raise F5ModuleError(resp.content)
893
894 def remove_from_device(self):
895 uri = "https://{0}:{1}/mgmt/tm/apm/acl/{2}".format(
896 self.client.provider['server'],
897 self.client.provider['server_port'],
898 transform_name(self.want.partition, self.want.name)
899 )
900 response = self.client.api.delete(uri)
901
902 if response.status in [200, 201]:
903 return True
904 raise F5ModuleError(response.content)
905
906 def read_current_from_device(self):
907 uri = "https://{0}:{1}/mgmt/tm/apm/acl/{2}".format(
908 self.client.provider['server'],
909 self.client.provider['server_port'],
910 transform_name(self.want.partition, self.want.name)
911 )
912 resp = self.client.api.get(uri)
913 try:
914 response = resp.json()
915 except ValueError as ex:
916 raise F5ModuleError(str(ex))
917
918 if resp.status in [200, 201] or 'code' in response and response['code'] in [200, 201]:
919 return ApiParameters(params=response)
920 raise F5ModuleError(resp.content)
921
922
923 class ArgumentSpec(object):
924 def __init__(self):
925 self.supports_check_mode = True
926 argument_spec = dict(
927 name=dict(required=True),
928 acl_order=dict(type='int'),
929 description=dict(),
930 path_match_case=dict(type='bool'),
931 type=dict(
932 choices=['static', 'dynamic'],
933 ),
934 entries=dict(
935 type='list',
936 elements='dict',
937 options=dict(
938 action=dict(
939 choices=['allow', 'reject', 'discard', 'continue'],
940 required=True
941 ),
942 dst_port=dict(),
943 dst_port_range=dict(),
944 src_port=dict(),
945 src_port_range=dict(),
946 dst_addr=dict(),
947 dst_mask=dict(),
948 src_addr=dict(),
949 src_mask=dict(),
950 scheme=dict(
951 choices=['any', 'https', 'http']
952 ),
953 protocol=dict(
954 choices=['tcp', 'icmp', 'udp', 'all']
955 ),
956 host_name=dict(),
957 paths=dict(),
958 log=dict(
959 choices=['packet', 'none']
960 ),
961 ),
962 mutually_exclusive=[
963 ['dst_port', 'dst_port_range'],
964 ['src_port', 'src_port_range'],
965 ],
966 ),
967 partition=dict(
968 default='Common',
969 fallback=(env_fallback, ['F5_PARTITION'])
970 ),
971 state=dict(
972 default='present',
973 choices=['present', 'absent']
974 )
975 )
976 self.argument_spec = {}
977 self.argument_spec.update(f5_argument_spec)
978 self.argument_spec.update(argument_spec)
979
980
981 def main():
982 spec = ArgumentSpec()
983
984 module = AnsibleModule(
985 argument_spec=spec.argument_spec,
986 supports_check_mode=spec.supports_check_mode,
987 )
988
989 try:
990 mm = ModuleManager(module=module)
991 results = mm.exec_module()
992 module.exit_json(**results)
993 except F5ModuleError as ex:
994 module.fail_json(msg=str(ex))
995
996
997 if __name__ == '__main__':
998 main()