Debian Codegraph @

ansible_collections/f5networks/f5_modules/plugins/modules/bigip_policy_rule.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
9 __metaclass__ = type
10
11
12 DOCUMENTATION = r'''
13 ---
14 module: bigip_policy_rule
15 short_description: Manage LTM policy rules on a BIG-IP
16 description:
17 - This module manages LTM policy rules on a BIG-IP.
18 version_added: "1.0.0"
19 options:
20 name:
21 description:
22 - The name of the rule.
23 type: str
24 required: True
25 policy:
26 description:
27 - The name of the policy with which you want to associate this rule.
28 type: str
29 required: True
30 replace_with:
31 description:
32 - Specifies if the C(conditions)/C(actions) given by the user should overwrite what exists on the device.
33 - The option is useful when a subset of C(conditions)/C(actions) needs to be removed. This option is similar to the
34 replace-all-with flag available in TMSH commands.
35 - Using this option is not idempotent.
36 type: bool
37 default: false
38 rule_order:
39 description:
40 - Specifies a number that indicates the order of this rule relative to other rules in the policy.
41 - When not set, the device sets the parameter to 0.
42 - If there are rules with the same rule order number, the device uses rule names
43 to determine how the rules are ordered.
44 - The lower the number, the lower the rule is in the general order, with the lowest number C(0) being the
45 topmost rule.
46 - Valid range of values is between C(0) and C(4294967295) inclusive.
47 type: int
48 version_added: "1.10.0"
49 description:
50 description:
51 - Description of the policy rule.
52 type: str
53 actions:
54 description:
55 - The actions you want the policy rule to perform.
56 - The available attributes vary by the action, however, each action requires
57 you specify a C(type).
58 - These conditions can be specified in any order. Despite the fact they are in a list,
59 the order in the list does not matter to the BIG-IP.
60 type: list
61 elements: dict
62 suboptions:
63 type:
64 description:
65 - The action type. This value controls which of the following options are required.
66 - When C(type) is C(forward), the system associates a given C(pool), or C(virtual),
67 or C(node) with this rule.
68 - When C(type) is C(enable), the system associates a given C(asm_policy) with
69 this rule.
70 - When C(type) is C(ignore), the system removes all existing actions from this
71 rule.
72 - When C(type) is C(redirect), the system redirects an HTTP request to a different URL.
73 - When C(type) is C(reset), the system resets the connection upon C(event).
74 - When C(type) is C(persist), the system associates C(cookie_insert) and C(cookie_expiry) with this rule.
75 - When C(type) is C(set_variable), the system sets a variable based on the evaluated Tcl C(expression) based on C(event).
76 - When C(type) is C(remove), the system removes C(http_set_cookie), C(http_referer), C(http_header) or C(http_cookie) with this rule.
77 - When C(type) is C(insert), the system inserts C(http_set_cookie), C(http_referer), C(http_header) or C(http_cookie) with this rule.
78 - When C(type) is C(replace), the system replaces C(http_connect), C(http_referer), C(http_header), C(http_uri) or C(http_host) with this rule.
79 - When C(type) is C(disable), the system disables C(disable_target) with this rule.
80 type: str
81 required: true
82 choices:
83 - forward
84 - enable
85 - ignore
86 - redirect
87 - reset
88 - persist
89 - set_variable
90 - remove
91 - insert
92 - replace
93 - disable
94 pool:
95 description:
96 - Pool to which you want to forward traffic.
97 - This parameter is only valid with the C(forward) type.
98 type: str
99 virtual:
100 description:
101 - Virtual server to which you want to forward traffic.
102 - This parameter is only valid with the C(forward) type.
103 type: str
104 node:
105 description:
106 - Node to which you want to forward traffic.
107 - This parameter is only valid with the C(forward) type.
108 type: str
109 version_added: "1.2.0"
110 disable_target:
111 description:
112 - Target you want to disable.
113 - This parameter is only valid with the C(disable) type.
114 type: str
115 version_added: "1.8.0"
116 choices:
117 - server_ssl
118 - persist
119 - asm
120 asm_policy:
121 description:
122 - ASM policy to enable.
123 - This parameter is only valid with the C(enable) type.
124 type: str
125 location:
126 description:
127 - The new URL for which a redirect response is sent.
128 - A Tcl command substitution can be used for this field.
129 type: str
130 event:
131 description:
132 - Events on which actions, such as reset and forward, can be triggered.
133 - With the C(set_variable) action, it is used for specifying
134 an action event, such as request or response.
135 - "Valid event choices for C(forward) action type are: client_accepted, proxy_request
136 request, ssl_client_hello and ssl_client_server_hello_send."
137 - "Valid event choices for C(reset) acton type are: client_accepted, proxy_connect
138 proxy_request, proxy_response, request, response, server_connected, ssl_client_hello,
139 ssl_client_server_hello_send, ssl_server_handshake, ssl_server_hello, websocket_request,
140 websocket_response."
141 - "Valid event choices for C(disable) acton type are: client_accepted, proxy_connect
142 proxy_request, proxy_response, request, server_connected."
143 type: str
144 expression:
145 description:
146 - A Tcl expression used with the C(set_variable) action.
147 type: str
148 variable_name:
149 description:
150 - Variable name used with the C(set_variable) action.
151 type: str
152 cookie_insert:
153 description:
154 - Cookie name on which you want to persist.
155 - This parameter is only valid with the C(persist) type.
156 type: str
157 version_added: "1.1.0"
158 cookie_expiry:
159 description:
160 - Optional argument, specifying the time for which the session is persisted.
161 - This parameter is only valid with the C(persist) type.
162 type: int
163 version_added: "1.1.0"
164 http_header:
165 description:
166 - HTTP Header that you want to remove or insert.
167 - This parameter is only valid with the C(remove), C(insert) and C(replace) type.
168 type: dict
169 suboptions:
170 event:
171 description:
172 - Type of event when the C(http_header) is removed, replaced, or inserted.
173 - The C(request) and C(response) events are only choices with C(remove) and C(insert) type.
174 - All of events are valid with C(replace) type action.
175 type: str
176 required: True
177 choices:
178 - request
179 - response
180 - proxy_connect
181 - proxy_request
182 - proxy_response
183 name:
184 description:
185 - The name of C(http_header).
186 type: str
187 required: True
188 value:
189 description:
190 - The value of C(http_header).
191 - Mandatory parameter when configured with C(insert) or C(replace) type.
192 type: str
193 version_added: "1.8.0"
194 http_referer:
195 description:
196 - HTTP Referer header you want to remove, replace, or insert.
197 - This parameter is only valid with the C(remove), C(insert) and C(replace) type.
198 type: dict
199 suboptions:
200 event:
201 description:
202 - Type of event when the c(http_referer) is removed, replaced, or inserted.
203 required: True
204 type: str
205 choices:
206 - request
207 - proxy_connect
208 - proxy_request
209 value:
210 description:
211 - The value of C(http_referer).
212 - This is a mandatory parameter when configured with C(insert) type action.
213 - This parameter is ignored for the C(remove) type.
214 - This parameter is optional for the C(replace) type.
215 type: str
216 version_added: "1.8.0"
217 http_set_cookie:
218 description:
219 - HTTP Set-Cookie header you want to remove or insert.
220 - This parameter is only valid with the C(remove) or c(insert) type.
221 type: dict
222 suboptions:
223 name:
224 description:
225 - The name of C(http_set_cookie).
226 type: str
227 required: True
228 value:
229 description:
230 - The value of C(http_set_cookie).
231 - This is a mandatory parameter when configured with C(insert) type action.
232 type: str
233 version_added: "1.8.0"
234 http_cookie:
235 description:
236 - HTTP Cookie header you want to remove or insert.
237 - This parameter is only valid with the C(remove) and C(insert) type.
238 type: dict
239 suboptions:
240 event:
241 description:
242 - Type of event when the C(http_cookie) is removed or inserted.
243 type: str
244 required: True
245 choices:
246 - request
247 - proxy_connect
248 - proxy_request
249 name:
250 description:
251 - The name of C(http_cookie).
252 type: str
253 required: True
254 value:
255 description:
256 - The value of C(http_cookie).
257 - This is a mandatory parameter when configured with C(insert) type action.
258 type: str
259 version_added: "1.8.0"
260 http_connect:
261 description:
262 - HTTP Connect header you want to replace.
263 - This parameter is only valid with the C(replace) type.
264 type: dict
265 suboptions:
266 event:
267 description:
268 - Type of event when the C(http_connect) header is replaced.
269 required: True
270 type: str
271 choices:
272 - client_accepted
273 - proxy_connect
274 - proxy_request
275 - proxy_response
276 - request
277 - server_connected
278 - ssl_client_hello
279 value:
280 description:
281 - The value of C(http_connect).
282 type: str
283 required: True
284 port:
285 description:
286 - The port number.
287 - If a port number is not provided, the value is set to 0 by default.
288 - Be explicit when defining rules, so the system does not override port values.
289 type: int
290 version_added: "1.8.0"
291 http_host:
292 description:
293 - HTTP Host header you want to replace.
294 - This parameter is only valid with the C(replace) type.
295 type: dict
296 suboptions:
297 event:
298 description:
299 - Type of event when the C(http_host) is replaced.
300 type: str
301 required: True
302 choices:
303 - request
304 - proxy_connect
305 - proxy_request
306 value:
307 description:
308 - The value of C(http_host).
309 type: str
310 required: True
311 version_added: "1.8.0"
312 http_uri:
313 description:
314 - Replaces HTTP URI, path, or string.
315 - This parameter is only valid with the C(replace) type.
316 type: dict
317 suboptions:
318 event:
319 description:
320 - Type of event when the C(http_uri) is replaced.
321 type: str
322 required: True
323 choices:
324 - request
325 - proxy_connect
326 - proxy_request
327 type:
328 description:
329 - Specifies the part of the C(http_uri) to be replaced.
330 type: str
331 required: True
332 choices:
333 - path
334 - query_string
335 - full_string
336 value:
337 description:
338 - The value of C(http_uri).
339 type: str
340 required: True
341 version_added: "1.8.0"
342 conditions:
343 description:
344 - A list of attributes that describe the condition.
345 - See sub-options for details on how to construct each list entry.
346 - The ordering of this list is important, the module ensures the order is
347 kept when modifying the task.
348 - The following sub-options are not required for all condition types,
349 read the description for more details.
350 - These conditions can be specified in any order. Despite the fact they are in a list,
351 the order in the list does not matter to the BIG-IP.
352 type: list
353 elements: dict
354 suboptions:
355 type:
356 description:
357 - The condition type. This value controls which of the following options are required.
358 - "When C(type) is C(http_uri), the valid choices are: C(path_begins_with_any), C(path_contains) or
359 C(path_is_any)."
360 - "When C(type) is C(http_host), the valid choices are: C(host_is_any), C(host_is_not_any), C(host_contains)
361 C(host_begins_with_any), C(host_begins_not_with_any), C(host_ends_with_any) or C(host_ends_not_with_any)"
362 - "When C(type) is C(http_header), the C(header_name) parameter is mandatory and the valid choice is:
363 C(header_is_any)."
364 - "When C(type) is C(http_method), the valid choices are: C(method_matches_with_any)."
365 - When C(type) is C(all_traffic), the system removes all existing conditions from
366 this rule.
367 type: str
368 required: True
369 choices:
370 - http_uri
371 - all_traffic
372 - http_host
373 - http_header
374 - http_method
375 - ssl_extension
376 - tcp
377 path_begins_with_any:
378 description:
379 - A list of strings of characters with which the HTTP URI should begin.
380 - This parameter is only valid with the C(http_uri) type.
381 type: list
382 elements: str
383 path_contains:
384 description:
385 - A list of strings of characters the HTTP URI should contain.
386 - This parameter is only valid with the C(http_uri) type.
387 type: list
388 elements: str
389 version_added: "1.8.0"
390 path_is_any:
391 description:
392 - A list of strings of characters the HTTP URI should match.
393 - This parameter is only valid with the C(http_uri) type.
394 type: list
395 elements: str
396 version_added: "1.8.0"
397 host_is_any:
398 description:
399 - A list of strings of characters the HTTP Host should match.
400 - This parameter is only valid with the C(http_host) type.
401 type: list
402 elements: str
403 host_is_not_any:
404 description:
405 - A list of strings of characters the HTTP Host should not match.
406 - This parameter is only valid with the C(http_host) type.
407 type: list
408 elements: str
409 host_contains:
410 description:
411 - A list of strings of characters the HTTP Host contain.
412 - This parameter is only valid with the C(http_host) type.
413 type: list
414 elements: str
415 version_added: "1.23.0"
416 host_begins_with_any:
417 description:
418 - A list of strings of characters with which the HTTP Host should begin.
419 - This parameter is only valid with the C(http_host) type.
420 type: list
421 elements: str
422 host_begins_not_with_any:
423 description:
424 - A list of strings of characters with which the HTTP Host should NOT begin.
425 - This parameter is only valid with the C(http_host) type.
426 type: list
427 elements: str
428 version_added: "1.22.0"
429 host_ends_not_with_any:
430 description:
431 - A list of strings of characters with which the HTTP Host should NOT begin.
432 - This parameter is only valid with the C(http_host) type.
433 type: list
434 elements: str
435 version_added: "1.22.0"
436 host_ends_with_any:
437 description:
438 - A list of strings of characters with which the HTTP Host should end.
439 - This parameter is only valid with the C(http_host) type.
440 type: list
441 elements: str
442 version_added: "1.8.0"
443 header_is_any:
444 description:
445 - A list of strings of characters the HTTP Header value should match.
446 - This parameter is only valid with the C(http_header) type.
447 type: list
448 elements: str
449 version_added: "1.8.0"
450 header_name:
451 description:
452 - A name of C(http_header).
453 - This parameter is only valid with the C(http_header) type.
454 type: str
455 version_added: "1.8.0"
456 method_matches_with_any:
457 description:
458 - A list of strings of characters the HTTP Method value should match.
459 - This parameter is only valid with the C(http_method) type.
460 type: list
461 elements: str
462 version_added: "1.10.0"
463 server_name_is_any:
464 description:
465 - A list of names that includes the server name.
466 - This parameter is only valid with the C(ssl_extension) type.
467 type: list
468 elements: str
469 server_name_is_not_any:
470 description:
471 - A list of names that does NOT include the server name.
472 - This parameter is only valid with the C(ssl_extension) type.
473 type: list
474 elements: str
475 version_added: "1.27.0"
476 server_name_begins_with_any:
477 description:
478 - A list of names with which the server name should begin.
479 - This parameter is only valid with the C(ssl_extension) type.
480 type: list
481 elements: str
482 version_added: "1.27.0"
483 server_name_begins_not_with_any:
484 description:
485 - A list of names with which the server name should NOT begin.
486 - This parameter is only valid with the C(ssl_extension) type.
487 type: list
488 elements: str
489 version_added: "1.27.0"
490 server_name_ends_with_any:
491 description:
492 - A list of names with which the server name should end.
493 - This parameter is only valid with the C(ssl_extension) type.
494 type: list
495 elements: str
496 version_added: "1.27.0"
497 server_name_ends_not_with_any:
498 description:
499 - A list of names with which the server name should NOT end.
500 - This parameter is only valid with the C(ssl_extension) type.
501 type: list
502 elements: str
503 version_added: "1.27.0"
504 server_name_contains:
505 description:
506 - A list of names the server name should contain.
507 - This parameter is only valid with the C(ssl_extension) type.
508 type: list
509 elements: str
510 version_added: "1.27.0"
511 address_matches_with_any:
512 description:
513 - A list of IP Subnet address strings that the IP address should match.
514 - This parameter is only valid with the C(tcp) type.
515 type: list
516 elements: str
517 version_added: "1.8.0"
518 address_matches_with_datagroup:
519 description:
520 - A list of internal data group strings that the IP address should match.
521 - This parameter is only valid with the C(tcp) type.
522 type: list
523 elements: str
524 version_added: "1.8.0"
525 address_matches_with_external_datagroup:
526 description:
527 - A list of external data group strings that the IP address should match.
528 - This parameter is only valid with the C(tcp) type.
529 type: list
530 elements: str
531 version_added: "1.10.0"
532 event:
533 description:
534 - Events on which conditions type match rules can be triggered.
535 - Supported only for C(http_header), C(http_method), C(ssl_extension) and C(tcp).
536 - "Valid choices for C(http_header) condition types are: C(proxy_connect),
537 C(proxy_request), C(proxy_response), C(request) and C(response)."
538 - "Valid choices for C(http_method) condition types are: C(proxy_connect),
539 C(proxy_request), C(proxy_response), C(request) and C(response)."
540 - "Valid choices for C(tcp) condition types are: C(request), C(client_accepted),
541 C(proxy_connect), C(proxy_request), C(proxy_response), C(ssl_client_hello), and
542 C(ssl_client_server_hello_send)."
543 - "Valid choices for C(ssl_extension) are: C(ssl_client_hello), and C(ssl_client_server_hello_send)."
544 type: str
545 state:
546 description:
547 - When C(present), ensures the key is uploaded to the device. When
548 C(absent), ensures the key is removed from the device. If the key
549 is currently in use, the module will not be able to remove the key.
550 type: str
551 choices:
552 - present
553 - absent
554 default: present
555 partition:
556 description:
557 - Device partition on which to manage resources.
558 type: str
559 default: Common
560 extends_documentation_fragment: f5networks.f5_modules.f5
561 requirements:
562 - BIG-IP >= v12.1.0
563 author:
564 - Tim Rupp (@caphrim007)
565 - Wojciech Wypior (@wojtek0806)
566 '''
567
568 EXAMPLES = r'''
569 - name: Create policies
570 bigip_policy:
571 name: Policy-Foo
572 state: present
573 provider:
574 server: lb.mydomain.com
575 user: admin
576 password: secret
577 delegate_to: localhost
578
579 - name: Add a rule to the new policy
580 bigip_policy_rule:
581 policy: Policy-Foo
582 name: rule3
583 conditions:
584 - type: http_uri
585 path_begins_with_any:
586 - /ABC
587 actions:
588 - type: forward
589 pool: pool-svrs
590 provider:
591 server: lb.mydomain.com
592 user: admin
593 password: secret
594 delegate_to: localhost
595
596 - name: Add multiple rules to the new policy
597 bigip_policy_rule:
598 policy: Policy-Foo
599 name: "{{ item.name }}"
600 conditions: "{{ item.conditions }}"
601 actions: "{{ item.actions }}"
602 provider:
603 server: lb.mydomain.com
604 user: admin
605 password: secret
606 delegate_to: localhost
607 loop:
608 - name: rule1
609 actions:
610 - type: forward
611 pool: pool-svrs
612 conditions:
613 - type: http_uri
614 path_begins_with_any:
615 - /euro
616 - name: rule2
617 actions:
618 - type: forward
619 pool: pool-svrs
620 conditions:
621 - type: http_uri
622 path_begins_with_any:
623 - /HomePage/
624 - name: rule3
625 actions:
626 - type: set_variable
627 variable_name: user-agent
628 expression: tcl:[HTTP::header User-Agent]
629 event: request
630 conditions:
631 - type: http_uri
632 path_begins_with_any:
633 - /HomePage/
634
635 - name: Remove all rules and conditions from the rule
636 bigip_policy_rule:
637 policy: Policy-Foo
638 name: rule1
639 conditions:
640 - type: all_traffic
641 actions:
642 - type: ignore
643 provider:
644 server: lb.mydomain.com
645 user: admin
646 password: secret
647 delegate_to: localhost
648 '''
649
650 RETURN = r'''
651 actions:
652 description: The new list of actions applied to the rule.
653 returned: changed
654 type: complex
655 contains:
656 type:
657 description: The action type.
658 returned: changed
659 type: str
660 sample: forward
661 pool:
662 description: Pool for forwarding to.
663 returned: changed
664 type: str
665 sample: foo-pool
666 sample: hash/dictionary of values
667 conditions:
668 description: The new list of conditions applied to the rule.
669 returned: changed
670 type: complex
671 contains:
672 type:
673 description: The condition type.
674 returned: changed
675 type: str
676 sample: http_uri
677 path_begins_with_any:
678 description: List of strings with which the URI begins.
679 returned: changed
680 type: list
681 sample: [foo, bar]
682 sample: hash/dictionary of values
683 description:
684 description: The new description of the rule.
685 returned: changed
686 type: str
687 sample: My rule
688 rule_order:
689 description: Specifies a number that indicates the order of this rule relative to other rules in the policy.
690 returned: changed
691 type: int
692 sample: 10
693 '''
694
695 from datetime import datetime
696
697 from ansible.module_utils.basic import (
698 AnsibleModule, env_fallback
699 )
700 from ansible.module_utils.six import iteritems
701
702 from ..module_utils.bigip import F5RestClient
703 from ..module_utils.common import (
704 F5ModuleError, AnsibleF5Parameters, transform_name, f5_argument_spec, fq_name
705 )
706 from ..module_utils.compare import compare_complex_list
707 from ..module_utils.icontrol import tmos_version
708 from ..module_utils.teem import send_teem
709
710
711 class Parameters(AnsibleF5Parameters):
712 api_map = {
713 'actionsReference': 'actions',
714 'conditionsReference': 'conditions',
715 'ordinal': 'rule_order',
716 }
717 api_attributes = [
718 'description',
719 'actions',
720 'conditions',
721 'ordinal',
722 ]
723
724 updatables = [
725 'actions',
726 'conditions',
727 'description',
728 'rule_order',
729 ]
730
731 returnables = [
732 'description',
733 'action',
734 'conditions',
735 'rule_order',
736 ]
737
738 @property
739 def name(self):
740 return self._values.get('name', None)
741
742 @property
743 def description(self):
744 return self._values.get('description', None)
745
746 @property
747 def policy(self):
748 if self._values['policy'] is None:
749 return None
750 return self._values['policy']
751
752
753 class ApiParameters(Parameters):
754 def _remove_internal_keywords(self, resource):
755 items = [
756 'kind', 'generation', 'selfLink', 'poolReference', 'offset', 'datagroupReference'
757 ]
758 for item in items:
759 try:
760 del resource[item]
761 except KeyError:
762 pass
763
764 @property
765 def actions(self):
766 result = []
767 if self._values['actions'] is None or 'items' not in self._values['actions']:
768 return [dict(type='ignore')]
769 for item in self._values['actions']['items']:
770 action = dict()
771 self._remove_internal_keywords(item)
772 if 'forward' in item:
773 action.update(item)
774 action['type'] = 'forward'
775 del action['forward']
776 elif 'enable' in item:
777 action.update(item)
778 action['type'] = 'enable'
779 del action['enable']
780 elif 'disable' in item:
781 action.update(item)
782 action['type'] = 'disable'
783 del action['disable']
784 elif 'redirect' in item:
785 action.update(item)
786 action['type'] = 'redirect'
787 del action['redirect']
788 elif 'setVariable' in item:
789 action.update(item)
790 action['type'] = 'set_variable'
791 del action['fullPath']
792 del action['code']
793 del action['expirySecs']
794 del action['length']
795 del action['port']
796 del action['status']
797 del action['vlanId']
798 del action['timeout']
799 elif 'shutdown' in item:
800 action.update(item)
801 action['type'] = 'reset'
802 del action['shutdown']
803 elif 'persist' in item:
804 action.update(item)
805 action['type'] = 'persist'
806 del action['persist']
807 elif 'remove' in item:
808 action.update(item)
809 action['type'] = 'remove'
810 action.pop('fullPath', None)
811 action.pop('code', None)
812 action.pop('expirySecs', None)
813 action.pop('length', None)
814 action.pop('port', None)
815 action.pop('status', None)
816 action.pop('vlanId', None)
817 action.pop('timeout', None)
818 action.pop('offset', None)
819 del action['remove']
820 elif 'insert' in item:
821 action.update(item)
822 action['type'] = 'insert'
823 action.pop('fullPath', None)
824 action.pop('code', None)
825 action.pop('expirySecs', None)
826 action.pop('length', None)
827 action.pop('port', None)
828 action.pop('status', None)
829 action.pop('vlanId', None)
830 action.pop('timeout', None)
831 action.pop('offset', None)
832 del action['insert']
833 elif 'replace' in item:
834 action.update(item)
835 action['type'] = 'replace'
836 action.pop('fullPath', None)
837 action.pop('code', None)
838 action.pop('expirySecs', None)
839 action.pop('length', None)
840 action.pop('status', None)
841 action.pop('vlanId', None)
842 action.pop('timeout', None)
843 action.pop('offset', None)
844 if 'httpConnect' not in action:
845 action.pop('port', None)
846 del action['replace']
847 result.append(action)
848 result = sorted(result, key=lambda x: x['name'])
849 return result
850
851 @property
852 def conditions(self):
853 result = []
854 if self._values['conditions'] is None or 'items' not in self._values['conditions']:
855 return [dict(type='all_traffic')]
856 for item in self._values['conditions']['items']:
857 action = dict()
858 self._remove_internal_keywords(item)
859 if 'httpUri' in item:
860 action.update(item)
861 action['type'] = 'http_uri'
862 del action['httpUri']
863
864 # Converts to common stringiness
865 #
866 # The tuple set "issubset" check that happens in the Difference
867 # engine does not recognize that a u'foo' and 'foo' are equal "enough"
868 # to consider them a subset. Therefore, we cast everything here to
869 # whatever the common stringiness is.
870 if 'values' in action:
871 action['values'] = [str(x) for x in action['values']]
872 elif 'httpHost' in item:
873 action.update(item)
874 action['type'] = 'http_host'
875 if 'values' in action:
876 action['values'] = [str(x) for x in action['values']]
877 del action['httpHost']
878 elif 'httpMethod' in item:
879 action.update(item)
880 action['type'] = 'http_method'
881 if 'values' in action:
882 action['values'] = [str(x) for x in action['values']]
883 del action['httpMethod']
884 elif 'httpHeader' in item:
885 action.update(item)
886 action['type'] = 'http_header'
887 if 'values' in action:
888 action['values'] = [str(x) for x in action['values']]
889 del action['httpHeader']
890 elif 'sslExtension' in item:
891 action.update(item)
892 action['type'] = 'ssl_extension'
893 if 'values' in action:
894 action['values'] = [str(x) for x in action['values']]
895 del action['sslExtension']
896 elif 'tcp' in item:
897 action.update(item)
898 action['type'] = 'tcp'
899 if 'values' in action:
900 action['values'] = [str(x) for x in action['values']]
901 result.append(action)
902 # Names contains the index in which the rule is at.
903 result = sorted(result, key=lambda x: x['name'])
904 return result
905
906
907 class ModuleParameters(Parameters):
908 @property
909 def rule_order(self):
910 if self._values['rule_order'] is None:
911 return None
912 if 0 < self._values['rule_order'] > 4294967295:
913 raise F5ModuleError(
914 "Specified number is out of valid range, correct range is between 0 and 4294967295."
915 )
916 return self._values['rule_order']
917
918 @property
919 def actions(self):
920 result = []
921 if self._values['actions'] is None:
922 return None
923 for idx, item in enumerate(self._values['actions']):
924 action = dict()
925 if 'name' in item:
926 action['name'] = str(item['name'])
927 else:
928 action['name'] = str(idx)
929 if item['type'] == 'forward':
930 self._handle_forward_action(action, item)
931 elif item['type'] == 'set_variable':
932 self._handle_set_variable_action(action, item)
933 elif item['type'] == 'enable':
934 self._handle_enable_action(action, item)
935 if item['type'] == 'disable':
936 self._handle_disable_action(action, item)
937 elif item['type'] == 'ignore':
938 return [dict(type='ignore')]
939 elif item['type'] == 'redirect':
940 self._handle_redirect_action(action, item)
941 elif item['type'] == 'reset':
942 self._handle_reset_action(action, item)
943 del action['shutdown']
944 elif item['type'] == 'persist':
945 self._handle_persist_action(action, item)
946 elif item['type'] == 'remove':
947 self._handle_remove_action(action, item)
948 elif item['type'] == 'insert':
949 self._handle_insert_action(action, item)
950 elif item['type'] == 'replace':
951 self._handle_replace_action(action, item)
952 result.append(action)
953 result = sorted(result, key=lambda x: x['name'])
954 return result
955
956 @property
957 def conditions(self):
958 result = []
959 if self._values['conditions'] is None:
960 return None
961 for idx, item in enumerate(self._values['conditions']):
962 action = dict()
963 if 'name' in item:
964 action['name'] = str(item['name'])
965 else:
966 action['name'] = str(idx)
967 if item['type'] == 'http_uri':
968 self._handle_http_uri_condition(action, item)
969 elif item['type'] == 'http_method':
970 self._handle_http_method_condition(action, item)
971 elif item['type'] == 'http_host':
972 self._handle_http_host_condition(action, item)
973 elif item['type'] == 'http_header':
974 self._handle_http_header_condition(action, item)
975 elif item['type'] == 'ssl_extension':
976 self._handle_ssl_extension_condition(action, item)
977 elif item['type'] == 'tcp':
978 self._handle_tcp_condition(action, item)
979 elif item['type'] == 'all_traffic':
980 return [dict(type='all_traffic')]
981 result.append(action)
982 result = sorted(result, key=lambda x: x['name'])
983 return result
984
985 def _handle_http_host_condition(self, action, item):
986 options = [
987 'host_begins_with_any', 'host_begins_not_with_any', 'host_ends_with_any',
988 'host_ends_not_with_any', 'host_is_any', 'host_is_not_any', 'host_contains'
989 ]
990 action['type'] = 'http_host'
991
992 if not any(x for x in options if x in item):
993 raise F5ModuleError(
994 "A 'host_begins_with_any', 'host_begins_not_with_any', 'host_ends_with_any', 'host_ends_not_with_any',"
995 "'host_is_any', 'host_contains, or 'host_is_not_any' must be specified "
996 "when the 'http_uri' type is used."
997 )
998
999 if 'host_begins_with_any' in item and item['host_begins_with_any'] is not None:
1000 if isinstance(item['host_begins_with_any'], list):
1001 values = item['host_begins_with_any']
1002 else:
1003 values = [item['host_begins_with_any']]
1004 action.update(dict(
1005 host=True,
1006 startsWith=True,
1007 values=values
1008 ))
1009 elif 'host_begins_not_with_any' in item and item['host_begins_not_with_any'] is not None:
1010 if isinstance(item['host_begins_not_with_any'], list):
1011 values = item['host_begins_not_with_any']
1012 else:
1013 values = [item['host_begins_not_with_any']]
1014 action.update({
1015 'host': True,
1016 'startsWith': True,
1017 'not': True,
1018 'values': values
1019 })
1020 elif 'host_ends_not_with_any' in item and item['host_ends_not_with_any'] is not None:
1021 if isinstance(item['host_ends_not_with_any'], list):
1022 values = item['host_ends_not_with_any']
1023 else:
1024 values = [item['host_ends_not_with_any']]
1025 action.update({
1026 'host': True,
1027 'endsWith': True,
1028 'not': True,
1029 'values': values
1030 })
1031 elif 'host_ends_with_any' in item and item['host_ends_with_any'] is not None:
1032 if isinstance(item['host_ends_with_any'], list):
1033 values = item['host_ends_with_any']
1034 else:
1035 values = [item['host_ends_with_any']]
1036 action.update(dict(
1037 host=True,
1038 endsWith=True,
1039 values=values
1040 ))
1041 elif 'host_is_any' in item and item['host_is_any'] is not None:
1042 if isinstance(item['host_is_any'], list):
1043 values = item['host_is_any']
1044 else:
1045 values = [item['host_is_any']]
1046 action.update(dict(
1047 equals=True,
1048 host=True,
1049 values=values
1050 ))
1051 elif 'host_is_not_any' in item and item['host_is_not_any'] is not None:
1052 if isinstance(item['host_is_not_any'], list):
1053 values = item['host_is_not_any']
1054 else:
1055 values = [item['host_is_not_any']]
1056 action.update({
1057 'equals': True,
1058 'host': True,
1059 'not': True,
1060 'values': values
1061 })
1062
1063 elif 'host_contains' in item and item['host_contains'] is not None:
1064 if isinstance(item['host_contains'], list):
1065 values = item['host_contains']
1066 else:
1067 values = [item['host_contains']]
1068 action.update(dict(
1069 host=True,
1070 contains=True,
1071 values=values
1072 ))
1073
1074 def _handle_http_method_condition(self, action, item):
1075 options = ['method_matches_with_any']
1076 action['type'] = 'http_method'
1077 event_map = dict(
1078 proxy_connect='proxyConnect',
1079 proxy_request='proxyRequest',
1080 proxy_response='proxyResponse',
1081 request='request',
1082 response='response',
1083 )
1084
1085 if not any(x for x in options if x in item):
1086 raise F5ModuleError(
1087 "A 'method_matches_with_any' must be specified when the 'http_method' type is used."
1088 )
1089
1090 if 'event' in item and item['event'] is not None:
1091 event = event_map.get(item['event'], None)
1092 if event:
1093 action[event] = True
1094
1095 if 'method_matches_with_any' in item and item['method_matches_with_any'] is not None:
1096 if isinstance(item['method_matches_with_any'], list):
1097 values = item['method_matches_with_any']
1098 else:
1099 values = [item['method_matches_with_any']]
1100 action.update(dict(
1101 startsWith=True,
1102 values=values
1103 ))
1104
1105 def _handle_http_uri_condition(self, action, item):
1106 action['type'] = 'http_uri'
1107 options = ['path_begins_with_any', 'path_contains', 'path_is_any']
1108
1109 if all(k not in item for k in options):
1110 raise F5ModuleError(
1111 "A 'path_begins_with_any', 'path_contains' or 'path_is_any' must be specified "
1112 "when the 'http_uri' type is used."
1113 )
1114
1115 if 'path_begins_with_any' in item and item['path_begins_with_any'] is not None:
1116 if isinstance(item['path_begins_with_any'], list):
1117 values = item['path_begins_with_any']
1118 else:
1119 values = [item['path_begins_with_any']]
1120 action.update(dict(
1121 path=True,
1122 startsWith=True,
1123 values=values
1124 ))
1125 elif 'path_contains' in item and item['path_contains'] is not None:
1126 if isinstance(item['path_contains'], list):
1127 values = item['path_contains']
1128 else:
1129 values = [item['path_contains']]
1130 action.update(dict(
1131 path=True,
1132 contains=True,
1133 values=values
1134 ))
1135 elif 'path_is_any' in item and item['path_is_any'] is not None:
1136 if isinstance(item['path_is_any'], list):
1137 values = item['path_is_any']
1138 else:
1139 values = [item['path_is_any']]
1140 action.update(dict(
1141 path=True,
1142 equals=True,
1143 values=values
1144 ))
1145
1146 def _handle_tcp_condition(self, action, item):
1147 options = [
1148 'address_matches_with_any', 'address_matches_with_datagroup', 'address_matches_with_external_datagroup'
1149 ]
1150 event_map = dict(
1151 client_accepted='clientAccepted',
1152 proxy_connect='proxyConnect',
1153 proxy_request='proxyRequest',
1154 proxy_response='proxyResponse',
1155 request='request',
1156 ssl_client_hello='sslClientHello',
1157 ssl_client_server_hello_send='sslClientServerhelloSend'
1158 )
1159 action['type'] = 'tcp'
1160 if all(k not in item for k in options):
1161 raise F5ModuleError(
1162 "A 'address_matches_with_any','address_matches_with_datagroup' or"
1163 "'address_matches_with_external_datagroup' must be specified when the 'tcp' type is used."
1164 )
1165 if 'address_matches_with_any' in item and item['address_matches_with_any'] is not None:
1166 if isinstance(item['address_matches_with_any'], list):
1167 values = item['address_matches_with_any']
1168 else:
1169 values = [item['address_matches_with_any']]
1170 action.update(dict(
1171 address=True,
1172 matches=True,
1173 values=values
1174 ))
1175 if 'address_matches_with_datagroup' in item and item['address_matches_with_datagroup'] is not None:
1176 if isinstance(item['address_matches_with_datagroup'], list):
1177 values = item['address_matches_with_datagroup']
1178 else:
1179 values = [item['address_matches_with_datagroup']]
1180 for value in values:
1181 action.update(dict(
1182 address=True,
1183 matches=True,
1184 datagroup=fq_name(self.partition, value)
1185 )
1186 )
1187 if 'address_matches_with_external_datagroup' in item and \
1188 item['address_matches_with_external_datagroup'] is not None:
1189 if isinstance(item['address_matches_with_external_datagroup'], list):
1190 values = item['address_matches_with_external_datagroup']
1191 else:
1192 values = [item['address_matches_with_external_datagroup']]
1193 for value in values:
1194 action.update(dict(
1195 address=True,
1196 matches=True,
1197 datagroup=fq_name(self.partition, value)
1198 )
1199 )
1200 if 'event' in item and item['event'] is not None:
1201 event = event_map.get(item['event'], None)
1202 if event:
1203 action[event] = True
1204
1205 def _handle_ssl_extension_condition(self, action, item):
1206 options = [
1207 'server_name_is_any', 'server_name_is_not_any', 'server_name_contains',
1208 'server_name_begins_with_any', 'server_name_begins_not_with_any',
1209 'server_name_ends_with_any', 'server_name_ends_not_with_any',
1210 ]
1211 action['type'] = 'ssl_extension'
1212 if 'server_name_is_any' in item and item['server_name_is_any'] is not None:
1213 if isinstance(item['server_name_is_any'], list):
1214 values = item['server_name_is_any']
1215 else:
1216 values = [item['server_name_is_any']]
1217 action.update(dict(
1218 equals=True,
1219 serverName=True,
1220 values=values
1221 ))
1222 if 'server_name_is_not_any' in item and item['server_name_is_not_any'] is not None:
1223 if isinstance(item['server_name_is_not_any'], list):
1224 values = item['server_name_is_not_any']
1225 else:
1226 values = [item['server_name_is_not_any']]
1227 action.update({
1228 'equals': True,
1229 'serverName': True,
1230 'not': True,
1231 'values': values
1232 })
1233 if 'server_name_begins_with_any' in item and item['server_name_begins_with_any'] is not None:
1234 if isinstance(item['server_name_begins_with_any'], list):
1235 values = item['server_name_begins_with_any']
1236 else:
1237 values = [item['server_name_begins_with_any']]
1238 action.update(dict(
1239 serverName=True,
1240 startsWith=True,
1241 values=values
1242 ))
1243 if 'server_name_begins_not_with_any' in item and item['server_name_begins_not_with_any'] is not None:
1244 if isinstance(item['server_name_begins_not_with_any'], list):
1245 values = item['server_name_begins_not_with_any']
1246 else:
1247 values = [item['server_name_begins_not_with_any']]
1248 action.update({
1249 'serverName': True,
1250 'startsWith': True,
1251 'not': True,
1252 'values': values
1253 })
1254 if 'server_name_ends_with_any' in item and item['server_name_ends_with_any'] is not None:
1255 if isinstance(item['server_name_ends_with_any'], list):
1256 values = item['server_name_ends_with_any']
1257 else:
1258 values = [item['server_name_ends_with_any']]
1259 action.update(dict(
1260 serverName=True,
1261 endsWith=True,
1262 values=values
1263 ))
1264 if 'server_name_ends_not_with_any' in item and item['server_name_ends_not_with_any'] is not None:
1265 if isinstance(item['server_name_ends_not_with_any'], list):
1266 values = item['server_name_ends_not_with_any']
1267 else:
1268 values = [item['server_name_ends_not_with_any']]
1269 action.update({
1270 'serverName': True,
1271 'endsWith': True,
1272 'not': True,
1273 'values': values
1274 })
1275 if 'server_name_contains' in item and item['server_name_contains'] is not None:
1276 if isinstance(item['server_name_contains'], list):
1277 values = item['server_name_contains']
1278 else:
1279 values = [item['server_name_contains']]
1280 action.update({
1281 'serverName': True,
1282 'contains': True,
1283 'values': values
1284 })
1285 if 'event' not in item:
1286 raise F5ModuleError(
1287 "An 'event' must be specified when the 'ssl_extension' condition is used."
1288 )
1289 elif 'ssl_client_hello' in item['event']:
1290 action.update(dict(
1291 sslClientHello=True
1292 ))
1293 elif 'ssl_server_hello' in item['event']:
1294 action.update(dict(
1295 sslServerHello=True
1296 ))
1297
1298 def _handle_http_header_condition(self, action, item):
1299 action['type'] = 'http_header'
1300 options = ['header_is_any']
1301 event_map = dict(
1302 proxy_connect='proxyConnect',
1303 proxy_request='proxyRequest',
1304 proxy_response='proxyResponse',
1305 request='request',
1306 response='response',
1307 )
1308 if 'header_name' not in item:
1309 raise F5ModuleError(
1310 "An 'header_name' must be specified when the 'http_header' condition is used."
1311 )
1312 if not any(x for x in options if x in item):
1313 raise F5ModuleError(
1314 "A 'header_is_any' must be specified when the 'http_header' type is used."
1315 )
1316 if 'event' in item and item['event'] is not None:
1317 event = event_map.get(item['event'], None)
1318 if event:
1319 action[event] = True
1320
1321 if 'header_is_any' in item:
1322 if isinstance(item['header_is_any'], list):
1323 values = item['header_is_any']
1324 else:
1325 values = [item['header_is_any']]
1326
1327 action.update(dict(
1328 equals=True,
1329 tmName=item['header_name'],
1330 values=values
1331 ))
1332
1333 def _handle_forward_action(self, action, item):
1334 """Handle the nuances of the forwarding type
1335
1336 Right now there is only a single type of forwarding that can be done. As that
1337 functionality expands, so-to will the behavior of this, and other, methods.
1338 Therefore, do not be surprised that the logic here is so rigid. It's deliberate.
1339
1340 :param action:
1341 :param item:
1342 :return:
1343 """
1344
1345 event_map = dict(
1346 client_accepted='clientAccepted',
1347 proxy_request='proxyRequest',
1348 request='request',
1349 ssl_client_hello='sslClientHello',
1350 ssl_client_server_hello_send='sslClientServerhelloSend'
1351 )
1352
1353 action['type'] = 'forward'
1354 options = ['pool', 'virtual', 'node']
1355 if not any(x for x in options if x in item):
1356 raise F5ModuleError(
1357 "A 'pool' or 'virtual' or 'node' must be specified when the 'forward' type is used."
1358 )
1359 if item.get('pool', None):
1360 action['pool'] = fq_name(self.partition, item['pool'])
1361 elif item.get('virtual', None):
1362 action['virtual'] = fq_name(self.partition, item['virtual'])
1363 elif item.get('node', None):
1364 action['node'] = item['node']
1365
1366 if 'event' in item and item['event'] is not None:
1367 event = event_map.get(item['event'], None)
1368 if event:
1369 action[event] = True
1370
1371 def _handle_set_variable_action(self, action, item):
1372 """Handle the nuances of the set_variable type
1373
1374 :param action:
1375 :param item:
1376 :return:
1377 """
1378 if 'expression' not in item and 'variable_name' not in item:
1379 raise F5ModuleError(
1380 "A 'variable_name' and 'expression' must be specified when the 'set_variable' type is used."
1381 )
1382
1383 if 'event' in item and item['event'] is not None:
1384 action[item['event']] = True
1385 else:
1386 action['request'] = True
1387 action.update(dict(
1388 type='set_variable',
1389 expression=item['expression'],
1390 tmName=item['variable_name'],
1391 setVariable=True,
1392 tcl=True
1393 ))
1394
1395 def _handle_enable_action(self, action, item):
1396 """Handle the nuances of the enable type
1397
1398 :param action:
1399 :param item:
1400 :return:
1401 """
1402 action['type'] = 'enable'
1403 if 'asm_policy' not in item:
1404 raise F5ModuleError(
1405 "An 'asm_policy' must be specified when the 'enable' type is used."
1406 )
1407 action.update(dict(
1408 policy=fq_name(self.partition, item['asm_policy']),
1409 asm=True
1410 ))
1411
1412 def _handle_disable_action(self, action, item):
1413 """Handle the nuances of the disable type
1414
1415 :param action:
1416 :param item:
1417 :return:
1418 """
1419
1420 target_map = dict(
1421 server_ssl='serverSsl',
1422 persist='persist',
1423 asm='asm'
1424 )
1425 event_map = dict(
1426 client_accepted='clientAccepted',
1427 proxy_connect='proxyConnect',
1428 proxy_request='proxyRequest',
1429 proxy_response='proxyResponse',
1430 request='request',
1431 server_connected='serverConnected',
1432 )
1433
1434 action['type'] = 'disable'
1435 if 'disable_target' not in item:
1436 raise F5ModuleError(
1437 "An 'disable_target' must be specified when the 'enable' type is used."
1438 )
1439 if 'event' in item and item['event'] is not None:
1440 event = event_map.get(item['event'], None)
1441 if event:
1442 action[event] = True
1443
1444 action[target_map[item['disable_target']]] = True
1445
1446 def _handle_redirect_action(self, action, item):
1447 """Handle the nuances of the redirect type
1448
1449 :param action:
1450 :param item:
1451 :return:
1452 """
1453 action['type'] = 'redirect'
1454 if 'location' not in item:
1455 raise F5ModuleError(
1456 "A 'location' must be specified when the 'redirect' type is used."
1457 )
1458 action.update(
1459 location=item['location'],
1460 httpReply=True,
1461 )
1462
1463 def _handle_reset_action(self, action, item):
1464 """Handle the nuances of the reset type
1465
1466 :param action:
1467 :param item:
1468 :return:
1469 """
1470 event_map = dict(
1471 client_accepted='clientAccepted',
1472 proxy_connect='proxyConnect',
1473 proxy_request='proxyRequest',
1474 proxy_response='proxyResponse',
1475 request='request',
1476 response='response',
1477 server_connected='serverConnected',
1478 ssl_client_hello='sslClientHello',
1479 ssl_client_server_hello_send='sslClientServerhelloSend',
1480 ssl_server_handshake='sslServerHandshake',
1481 ssl_server_hello='sslServerHello',
1482 websocket_request='wsRequest',
1483 websocket_response='wsResponse'
1484 )
1485
1486 action['type'] = 'reset'
1487 if 'event' not in item:
1488 raise F5ModuleError(
1489 "An 'event' must be specified when the 'reset' type is used."
1490 )
1491 event = event_map.get(item['event'], None)
1492 if not event:
1493 raise F5ModuleError(
1494 "Invalid event type specified for reset action: {0},"
1495 "check module documentation for valid event types.".format(item['event'])
1496 )
1497
1498 action[event] = True
1499 action.update({
1500 'connection': True,
1501 'shutdown': True
1502 })
1503
1504 def _handle_persist_action(self, action, item):
1505 """Handle the nuances of the persist type
1506
1507 :param action:
1508 :param item:
1509 :return:
1510 """
1511 action['type'] = 'persist'
1512 if 'cookie_insert' not in item:
1513 raise F5ModuleError(
1514 "A 'cookie_insert' must be specified when the 'persist' type is used."
1515 )
1516 elif 'cookie_expiry' in item:
1517 action.update(
1518 cookieInsert=True,
1519 tmName=item['cookie_insert'],
1520 expiry=str(item['cookie_expiry'])
1521 )
1522 else:
1523 action.update(
1524 cookieInsert=True,
1525 tmName=item['cookie_insert']
1526 )
1527
1528 def _handle_remove_action(self, action, item):
1529 """Handle the nuances of the remove type
1530
1531 :param action:
1532 :param item:
1533 :return:
1534 """
1535
1536 action['type'] = 'remove'
1537 options = ['http_header', 'http_referer', 'http_set_cookie', 'http_cookie']
1538 if not any(x for x in options if x in item):
1539 raise F5ModuleError(
1540 "A 'http_header', 'http_referer', 'http_set_cookie' or 'http_cookie' must be specified when "
1541 "the 'remove' type is used."
1542 )
1543 if 'http_header' in item and item['http_header']:
1544 if item['http_header']['event'] == 'request':
1545 action.update(
1546 httpHeader=True,
1547 tmName=item['http_header']['name'],
1548 request=True
1549 )
1550 elif item['http_header']['event'] == 'response':
1551 action.update(
1552 httpHeader=True,
1553 tmName=item['http_header']['name'],
1554 response=True
1555 )
1556 else:
1557 action.update(
1558 httpHeader=True,
1559 tmName=item['http_header']['name']
1560 )
1561 if 'http_referer' in item and item['http_referer']:
1562 if item['http_referer']['event'] == 'request':
1563 action.update(
1564 httpReferer=True,
1565 request=True
1566 )
1567 if item['http_referer']['event'] == 'proxy_connect':
1568 action.update(
1569 httpReferer=True,
1570 proxyConnect=True
1571 )
1572 if item['http_referer']['event'] == 'proxy_request':
1573 action.update(
1574 httpReferer=True,
1575 proxyRequest=True
1576 )
1577 if 'http_cookie' in item and item['http_cookie']:
1578 if item['http_cookie']['event'] == 'request':
1579 action.update(
1580 httpCookie=True,
1581 tmName=item['http_cookie']['name'],
1582 request=True
1583 )
1584 elif item['http_cookie']['event'] == 'proxy_connect':
1585 action.update(
1586 httpCookie=True,
1587 tmName=item['http_cookie']['name'],
1588 proxyConnect=True
1589 )
1590 elif item['http_cookie']['event'] == 'proxy_request':
1591 action.update(
1592 httpCookie=True,
1593 tmName=item['http_cookie']['name'],
1594 proxyRequest=True
1595 )
1596 else:
1597 action.update(
1598 httpCookie=True,
1599 tmName=item['http_cookie']['name']
1600 )
1601 if 'http_set_cookie' in item and item['http_set_cookie']:
1602 action.update(
1603 httpSetCookie=True,
1604 tmName=item['http_set_cookie']['name'],
1605 response=True
1606 )
1607
1608 def _handle_insert_action(self, action, item):
1609 """Handle the nuances of the insert type
1610
1611 :param action:
1612 :param item:
1613 :return:
1614 """
1615
1616 action['type'] = 'insert'
1617 options = ['http_header', 'http_referer', 'http_set_cookie', 'http_cookie']
1618 if not any(x for x in options if x in item):
1619 raise F5ModuleError(
1620 "A 'http_header', 'http_referer', 'http_set_cookie' or 'http_cookie' must be specified when "
1621 "the 'insert' type is used."
1622 )
1623
1624 if 'http_header' in item and item['http_header']:
1625 if item['http_header']['value'] is None:
1626 raise F5ModuleError(
1627 "The http_header value key is required when action is of type 'insert'."
1628 )
1629 if item['http_header']['event'] == 'request':
1630 action.update(
1631 httpHeader=True,
1632 tmName=item['http_header']['name'],
1633 value=item['http_header']['value'],
1634 request=True
1635 )
1636 elif item['http_header']['event'] == 'response':
1637 action.update(
1638 httpHeader=True,
1639 tmName=item['http_header']['name'],
1640 value=item['http_header']['value'],
1641 response=True
1642 )
1643 else:
1644 action.update(
1645 httpHeader=True,
1646 tmName=item['http_header']['name'],
1647 value=item['http_header']['value']
1648 )
1649 if 'http_referer' in item and item['http_referer']:
1650 if item['http_referer']['value'] is None:
1651 raise F5ModuleError(
1652 "The http_referer value key is required when action is of type 'insert'."
1653 )
1654 if item['http_referer']['event'] == 'request':
1655 action.update(
1656 httpReferer=True,
1657 value=item['http_referer']['value'],
1658 request=True
1659 )
1660 if item['http_referer']['event'] == 'proxy_connect':
1661 action.update(
1662 httpReferer=True,
1663 value=item['http_referer']['value'],
1664 proxyConnect=True
1665 )
1666 if item['http_referer']['event'] == 'proxy_request':
1667 action.update(
1668 httpReferer=True,
1669 value=item['http_referer']['value'],
1670 proxyRequest=True
1671 )
1672 if 'http_cookie' in item and item['http_cookie']:
1673 if item['http_cookie']['value'] is None:
1674 raise F5ModuleError(
1675 "The http_cookie value key is required when action is of type 'insert'."
1676 )
1677 if item['http_cookie']['event'] == 'request':
1678 action.update(
1679 httpCookie=True,
1680 tmName=item['http_cookie']['name'],
1681 value=item['http_cookie']['value'],
1682 request=True
1683 )
1684 elif item['http_cookie']['event'] == 'proxy_connect':
1685 action.update(
1686 httpCookie=True,
1687 tmName=item['http_cookie']['name'],
1688 value=item['http_cookie']['value'],
1689 proxyConnect=True
1690 )
1691 elif item['http_cookie']['event'] == 'proxy_request':
1692 action.update(
1693 httpCookie=True,
1694 tmName=item['http_cookie']['name'],
1695 value=item['http_cookie']['value'],
1696 proxyRequest=True
1697 )
1698 else:
1699 action.update(
1700 httpCookie=True,
1701 tmName=item['http_cookie']['name'],
1702 value=item['http_cookie']['value']
1703 )
1704 if 'http_set_cookie' in item and item['http_set_cookie']:
1705 if item['http_set_cookie']['value'] is None:
1706 raise F5ModuleError(
1707 "The http_set_cookie value key is required when action is of type 'insert'."
1708 )
1709 action.update(
1710 httpSetCookie=True,
1711 tmName=item['http_set_cookie']['name'],
1712 value=item['http_set_cookie']['value'],
1713 response=True
1714 )
1715
1716 def _handle_replace_action(self, action, item):
1717 """Handle the nuances of the replace type
1718
1719 :param action:
1720 :param item:
1721 :return:
1722 """
1723
1724 action['type'] = 'replace'
1725 options = ['http_header', 'http_referer', 'http_host', 'http_connect', 'http_uri']
1726 if not any(x for x in options if x in item):
1727 raise F5ModuleError(
1728 "A 'http_header', 'http_referer', 'http_host', 'http_connect' or 'http_uri' must be specified when "
1729 "the 'replace' type is used."
1730 )
1731 event_map = dict(
1732 client_accepted='clientAccepted',
1733 proxy_connect='proxyConnect',
1734 proxy_request='proxyRequest',
1735 proxy_response='proxyResponse',
1736 request='request',
1737 response='response',
1738 server_connected='serverConnected',
1739 ssl_client_hello='sslClientHello'
1740 )
1741 type_map = dict(
1742 path='path',
1743 query_string='queryString',
1744 full_string='value'
1745 )
1746 if 'http_header' in item and item['http_header']:
1747 if item['http_header']['value'] is None:
1748 raise F5ModuleError(
1749 "The http_header value key is required when action is of type 'replace'."
1750 )
1751 if item['http_header']['event'] is not None:
1752 action.update({
1753 'httpHeader': True,
1754 'tmName': item['http_header']['name'],
1755 'value': item['http_header']['value'],
1756 event_map[item['http_header']['event']]: True
1757 })
1758 else:
1759 action.update({
1760 'httpHeader': True,
1761 'tmName': item['http_header']['name'],
1762 'value': item['http_header']['value']
1763 })
1764 if 'http_referer' in item and item['http_referer']:
1765 if item['http_referer']['value'] is not None:
1766 action.update({
1767 'httpReferer': True,
1768 'value': item['http_referer']['value'],
1769 event_map[item['http_referer']['event']]: True
1770 })
1771 else:
1772 action.update({
1773 'httpReferer': True,
1774 event_map[item['http_referer']['event']]: True
1775 })
1776 if 'http_connect' in item and item['http_connect']:
1777 if item['http_connect']['port'] is None:
1778 action.update({
1779 'httpConnect': True,
1780 'host': item['http_connect']['value'],
1781 'port': 0,
1782 event_map[item['http_connect']['event']]: True
1783 })
1784 else:
1785 action.update({
1786 'httpConnect': True,
1787 'host': item['http_connect']['value'],
1788 'port': item['http_connect']['port'],
1789 event_map[item['http_connect']['event']]: True
1790 })
1791 if 'http_uri' in item and item['http_uri']:
1792 if item['http_uri']['event'] is not None:
1793 action.update({
1794 'httpUri': True,
1795 type_map[item['http_uri']['type']]: item['http_uri']['value'],
1796 event_map[item['http_uri']['event']]: True
1797 })
1798 else:
1799 action.update({
1800 'httpUri': True,
1801 type_map[item['http_uri']['type']]: item['http_uri']['value'],
1802 })
1803 if 'http_host' in item and item['http_host']:
1804 if item['http_host']['event'] is not None:
1805 action.update({
1806 'httpHost': True,
1807 'value': item['http_host']['value'],
1808 event_map[item['http_host']['event']]: True
1809 })
1810 else:
1811 action.update({
1812 'httpHost': True,
1813 'value': item['http_host']['value'],
1814 })
1815
1816
1817 class Changes(Parameters):
1818 def to_return(self):
1819 result = {}
1820 for returnable in self.returnables:
1821 try:
1822 result[returnable] = getattr(self, returnable)
1823 result = self._filter_params(result)
1824 except Exception:
1825 raise
1826 return result
1827
1828
1829 class ReportableChanges(Changes):
1830 event_map = dict(
1831 clientAccepted='client_accepted',
1832 proxyConnect='proxy_connect',
1833 proxyRequest='proxy_request',
1834 proxyResponse='proxy_response',
1835 request='request',
1836 response='response',
1837 serverConnected='server_connected',
1838 sslClientHello='ssl_client_hello'
1839 )
1840 uri_type_map = dict(
1841 path='path',
1842 queryString='query_string',
1843 value='full_string'
1844 )
1845
1846 returnables = [
1847 'description', 'actions', 'conditions'
1848 ]
1849
1850 def _map_value(self, item, t=False):
1851 if not t:
1852 for k in self.event_map.keys():
1853 if k in item:
1854 return k
1855 else:
1856 for k in self.uri_type_map.keys():
1857 if k in item:
1858 return k
1859 return None
1860
1861 @property
1862 def actions(self):
1863 result = []
1864 if self._values['actions'] is None:
1865 return [dict(type='ignore')]
1866 for item in self._values['actions']:
1867 action = dict()
1868 if 'forward' in item:
1869 action.update(item)
1870 action['type'] = 'forward'
1871 del action['forward']
1872 elif 'replace' in item:
1873 action.update(item)
1874 action['type'] = 'replace'
1875 if 'httpHeader' in item:
1876 event = self._map_value(item)
1877 if event:
1878 http_header = dict(event=self.event_map[event], name=action['tmName'], value=action['value'])
1879 action['http_header'] = http_header
1880 del action[event]
1881 else:
1882 http_header = dict(name=action['tmName'], value=action['value'])
1883 action['http_header'] = http_header
1884 del action['httpHeader']
1885 del action['value']
1886 del action['tmName']
1887 if 'httpReferer' in item:
1888 event = self._map_value(item)
1889 if event:
1890 if 'value' in item:
1891 http_ref = dict(event=self.event_map[event], value=action['value'])
1892 action['http_referer'] = http_ref
1893 del action['value']
1894 else:
1895 http_ref = dict(event=self.event_map[event])
1896 action['http_referer'] = http_ref
1897 del action[event]
1898 else:
1899 if 'value' in item:
1900 http_ref = dict(event=self.event_map[event], value=action['value'])
1901 action['http_referer'] = http_ref
1902 del action['value']
1903 del action['httpReferer']
1904 if 'httpConnect' in item:
1905 event = self._map_value(item)
1906 if event:
1907 if 'value' in item and 'port' in item:
1908 http_con = dict(event=self.event_map[event], value=action['value'], port=action['item'])
1909 action['http_connect'] = http_con
1910 del action['value']
1911 del action['port']
1912 elif 'value' in item and 'port' not in item:
1913 http_con = dict(event=self.event_map[event], value=action['value'])
1914 action['http_connect'] = http_con
1915 del action['value']
1916 elif 'value' not in item and 'port' in item:
1917 http_con = dict(event=self.event_map[event], port=action['port'])
1918 action['http_connect'] = http_con
1919 del action['port']
1920 else:
1921 http_con = dict(event=self.event_map[event])
1922 action['http_connect'] = http_con
1923 del action[event]
1924 else:
1925 if 'value' in item and 'port' in item:
1926 http_con = dict(value=action['value'], port=action['item'])
1927 action['http_connect'] = http_con
1928 del action['value']
1929 del action['port']
1930 elif 'value' in item and 'port' not in item:
1931 http_con = dict(value=action['value'])
1932 action['http_connect'] = http_con
1933 del action['value']
1934 elif 'value' not in item and 'port' in item:
1935 http_con = dict(port=action['port'])
1936 action['http_connect'] = http_con
1937 del action['port']
1938 del action['httpConnect']
1939 if 'httpUri' in item:
1940 event = self._map_value(item)
1941 kind = self._map_value(item, True)
1942 if event:
1943 http_uri = dict(event=self.event_map[event], type=self.uri_type_map[kind], value=action[kind])
1944 action['http_uri'] = http_uri
1945 del action[event]
1946 else:
1947 http_uri = dict(type=self.uri_type_map[kind], value=action[kind])
1948 action['http_uri'] = http_uri
1949 del action[kind]
1950 del action['httpUri']
1951 if 'httpHost' in item:
1952 event = self._map_value(item)
1953 if event:
1954 http_uri = dict(event=self.event_map[event], value=action['value'])
1955 action['http_uri'] = http_uri
1956 del action[event]
1957 else:
1958 http_uri = dict(value=action['value'])
1959 action['http_uri'] = http_uri
1960 del action['value']
1961 del action['httpHost']
1962 elif 'insert' in item:
1963 action.update(item)
1964 action['type'] = 'insert'
1965 if 'httpHeader' in item:
1966 if 'response' in item:
1967 http_header = dict(event='response', name=action['tmName'], value=action['value'])
1968 action['http_header'] = http_header
1969 del action['response']
1970 if 'request' in item:
1971 http_header = dict(event='request', name=action['tmName'], value=action['value'])
1972 action['http_header'] = http_header
1973 del action['request']
1974 del action['httpHeader']
1975 del action['tmName']
1976 if 'httpReferer' in item:
1977 if 'request' in item:
1978 http_ref = dict(event='request', value=action['value'])
1979 action['http_referer'] = http_ref
1980 del action['request']
1981 if 'proxyConnect' in item:
1982 http_ref = dict(event='proxy_connect', value=action['value'])
1983 action['http_referer'] = http_ref
1984 del action['proxyConnect']
1985 if 'proxyRequest' in item:
1986 http_ref = dict(event='proxy_request', value=action['value'])
1987 action['http_referer'] = http_ref
1988 del action['proxyRequest']
1989 del action['httpReferer']
1990 if 'httpCookie' in item:
1991 if 'request' in item:
1992 http_cookie = dict(event='request', name=action['tmName'], value=action['value'])
1993 action['http_cookie'] = http_cookie
1994 del action['request']
1995 if 'proxyConnect' in item:
1996 http_cookie = dict(event='proxy_connect', name=action['tmName'], value=action['value'])
1997 action['http_cookie'] = http_cookie
1998 del action['proxyConnect']
1999 if 'proxyRequest' in item:
2000 http_cookie = dict(event='proxy_request', name=action['tmName'], value=action['value'])
2001 action['http_cookie'] = http_cookie
2002 del action['proxyRequest']
2003 del action['httpCookie']
2004 del action['tmName']
2005 if 'httpSetCookie' in item:
2006 http_set_cookie = dict(name=action['tmName'], value=action['value'])
2007 action['http_set_cookie'] = http_set_cookie
2008 del action['response']
2009 del action['value']
2010 del action['tmName']
2011 del action['insert']
2012 del action['value']
2013 elif 'remove' in item:
2014 action.update(item)
2015 action['type'] = 'remove'
2016 if 'httpHeader' in item:
2017 if 'response' in item:
2018 http_header = dict(event='response', name=action['tmName'])
2019 action['http_header'] = http_header
2020 del action['response']
2021 if 'request' in item:
2022 http_header = dict(event='request', name=action['tmName'])
2023 action['http_header'] = http_header
2024 del action['request']
2025 del action['httpHeader']
2026 del action['tmName']
2027 if 'httpReferer' in item:
2028 if 'request' in item:
2029 http_ref = dict(event='request')
2030 action['http_referer'] = http_ref
2031 del action['request']
2032 if 'proxyConnect' in item:
2033 http_ref = dict(event='proxy_connect')
2034 action['http_referer'] = http_ref
2035 del action['proxyConnect']
2036 if 'proxyRequest' in item:
2037 http_ref = dict(event='proxy_request')
2038 action['http_referer'] = http_ref
2039 del action['proxyRequest']
2040 del action['httpReferer']
2041 if 'httpCookie' in item:
2042 if 'request' in item:
2043 http_cookie = dict(event='request', name=action['tmName'])
2044 action['http_cookie'] = http_cookie
2045 del action['request']
2046 if 'proxyConnect' in item:
2047 http_cookie = dict(event='proxy_connect', name=action['tmName'])
2048 action['http_cookie'] = http_cookie
2049 del action['proxyConnect']
2050 if 'proxyRequest' in item:
2051 http_cookie = dict(event='proxy_request', name=action['tmName'])
2052 action['http_cookie'] = http_cookie
2053 del action['proxyRequest']
2054 del action['httpCookie']
2055 del action['tmName']
2056 if 'httpSetCookie' in item:
2057 action['http_set_cookie'] = dict(name=action['tmName'])
2058 del action['response']
2059 del action['tmName']
2060 del action['remove']
2061 elif 'set_variable' in item:
2062 action.update(item)
2063 action['type'] = 'set_variable'
2064 del action['set_variable']
2065 elif 'enable' in item:
2066 action.update(item)
2067 action['type'] = 'enable'
2068 del action['enable']
2069 elif 'disable' in item:
2070 action.update(item)
2071 action['type'] = 'disable'
2072 if 'serverSsl' in action and action['serverSsl']:
2073 action['disable_target'] = 'server_ssl'
2074 del action['serverSsl']
2075 if 'persist' in action and action['persist']:
2076 action['disable_target'] = 'persist'
2077 del action['persist']
2078 if 'asm' in action and action['asm']:
2079 action['disable_target'] = 'asm'
2080 del action['asm']
2081 del action['enable']
2082 elif 'redirect' in item:
2083 action.update(item)
2084 action['type'] = 'redirect'
2085 del action['redirect']
2086 del action['httpReply']
2087 elif 'reset' in item:
2088 action.update(item)
2089 action['type'] = 'reset'
2090 del action['connection']
2091 del action['shutdown']
2092 elif 'persist' in item:
2093 action.update(item)
2094 action['type'] = 'persist'
2095 action['cookie_insert'] = action['tmName']
2096 if 'expiry' in item:
2097 action['cookie_expiry'] = int(action['expiry'])
2098 del action['expiry']
2099 del action['tmName']
2100 del action['persist']
2101 del action['cookieInsert']
2102 result.append(action)
2103 result = sorted(result, key=lambda x: x['name'])
2104 return result
2105
2106 @property
2107 def conditions(self):
2108 result = []
2109 if self._values['conditions'] is None:
2110 return [dict(type='all_traffic')]
2111 for item in self._values['conditions']:
2112 action = dict()
2113 if 'httpUri' in item:
2114 action.update(item)
2115 action['type'] = 'http_uri'
2116 del action['httpUri']
2117 elif 'httpMethod' in item:
2118 action.update(item)
2119 action['type'] = 'http_method'
2120 del action['httpMethod']
2121 elif 'httpHost' in item:
2122 action.update(item)
2123 action['type'] = 'http_host'
2124 del action['httpHost']
2125 elif 'httpHeader' in item:
2126 action.update(item)
2127 action['type'] = 'http_header'
2128 action['header_name'] = action['tmName']
2129 del action['httpHeader']
2130 del action['tmName']
2131 elif 'tcp' in item:
2132 action.update(item)
2133 action['type'] = 'tcp'
2134 del action['tcp']
2135 elif 'sslExtension' in item:
2136 action.update(item)
2137 action['type'] = 'ssl_extension'
2138 del action['sslExtension']
2139 result.append(action)
2140 # Names contains the index in which the rule is at.
2141 result = sorted(result, key=lambda x: x['name'])
2142 return result
2143
2144
2145 class UsableChanges(Changes):
2146 @property
2147 def actions(self):
2148 if self._values['actions'] is None:
2149 return None
2150 result = []
2151 for action in self._values['actions']:
2152 if 'type' not in action:
2153 continue
2154 if action['type'] == 'forward':
2155 action['forward'] = True
2156 del action['type']
2157 elif action['type'] == 'enable':
2158 action['enable'] = True
2159 del action['type']
2160 elif action['type'] == 'disable':
2161 action['disable'] = True
2162 del action['type']
2163 elif action['type'] == 'set_variable':
2164 action['setVariable'] = True
2165 action['tcl'] = True
2166 del action['type']
2167 elif action['type'] == 'ignore':
2168 result = []
2169 break
2170 elif action['type'] == 'redirect':
2171 action['httpReply'] = True
2172 action['redirect'] = True
2173 del action['type']
2174 elif action['type'] == 'reset':
2175 action['shutdown'] = True
2176 action['connection'] = True
2177 del action['type']
2178 elif action['type'] == 'persist':
2179 action['persist'] = True
2180 del action['type']
2181 elif action['type'] == 'remove':
2182 action['remove'] = True
2183 del action['type']
2184 elif action['type'] == 'insert':
2185 action['insert'] = True
2186 del action['type']
2187 elif action['type'] == 'replace':
2188 action['replace'] = True
2189 del action['type']
2190 result.append(action)
2191 return result
2192
2193 @property
2194 def conditions(self):
2195 if self._values['conditions'] is None:
2196 return None
2197 result = []
2198 for condition in self._values['conditions']:
2199 if 'type' not in condition:
2200 continue
2201 if condition['type'] == 'http_uri':
2202 condition['httpUri'] = True
2203 del condition['type']
2204 elif condition['type'] == 'http_method':
2205 condition['httpMethod'] = True
2206 del condition['type']
2207 elif condition['type'] == 'http_host':
2208 condition['httpHost'] = True
2209 del condition['type']
2210 elif condition['type'] == 'http_header':
2211 condition['httpHeader'] = True
2212 elif condition['type'] == 'tcp':
2213 condition['tcp'] = True
2214 del condition['type']
2215 elif condition['type'] == 'ssl_extension':
2216 condition['sslExtension'] = True
2217 del condition['type']
2218 elif condition['type'] == 'all_traffic':
2219 result = []
2220 break
2221 result.append(condition)
2222 return result
2223
2224
2225 class Difference(object):
2226 updatables = [
2227 'actions', 'conditions', 'description'
2228 ]
2229
2230 def __init__(self, want, have=None):
2231 self.want = want
2232 self.have = have
2233
2234 def compare(self, param):
2235 try:
2236 result = getattr(self, param)
2237 return result
2238 except AttributeError:
2239 return self.__default(param)
2240
2241 def __default(self, param):
2242 attr1 = getattr(self.want, param)
2243 try:
2244 attr2 = getattr(self.have, param)
2245 if attr1 != attr2:
2246 return attr1
2247 except AttributeError:
2248 return attr1
2249
2250 def to_tuple(self, items):
2251 result = []
2252 for x in items:
2253 tmp = [(str(k), str(v)) for k, v in iteritems(x)]
2254 result += tmp
2255 return result
2256
2257 def _diff_complex_items(self, want, have):
2258 if want == [] and have is None:
2259 return None
2260 if want is None:
2261 return None
2262 w = self.to_tuple(want)
2263 h = self.to_tuple(have)
2264 if set(w).issubset(set(h)):
2265 return None
2266 else:
2267 return want
2268
2269 @property
2270 def actions(self):
2271 if self.want.replace_with is True:
2272 return self.want.actions
2273 result = self._diff_complex_items(self.want.actions, self.have.actions)
2274 actioned = self._compare_complex_actions()
2275 if self._conditions_missing_default_rule_for_asm(result):
2276 raise F5ModuleError(
2277 "Valid options when using an ASM policy in a rule's 'enable' "
2278 "action include all_traffic, http_uri, or http_host."
2279 )
2280 if result is None and actioned is True:
2281 return self.want.actions
2282 return result
2283
2284 @property
2285 def conditions(self):
2286 if self.want.replace_with is True:
2287 return self.want.conditions
2288 result = self._diff_complex_items(self.want.conditions, self.have.conditions)
2289 return result
2290
2291 def _conditions_missing_default_rule_for_asm(self, want_actions):
2292 if want_actions is None:
2293 actions = self.have.actions
2294 else:
2295 actions = want_actions
2296 if actions is None:
2297 return False
2298 if any(x for x in actions if x['type'] == 'enable'):
2299 conditions = self._diff_complex_items(self.want.conditions, self.have.conditions)
2300 if conditions is None:
2301 return False
2302 if any(y for y in conditions if y['type'] not in ['all_traffic', 'http_uri', 'http_host', 'tcp']):
2303 return True
2304 return False
2305
2306 def _compare_complex_actions(self):
2307 types = ['insert', 'remove', 'replace']
2308 if self.want.actions:
2309 want = [item for item in self.want.actions if item['type'] in types]
2310 have = [item for item in self.have.actions if item['type'] in types]
2311 result = compare_complex_list(want, have)
2312 if result:
2313 return True
2314 return False
2315
2316
2317 class ModuleManager(object):
2318 def __init__(self, *args, **kwargs):
2319 self.module = kwargs.get('module', None)
2320 self.client = F5RestClient(**self.module.params)
2321 self.want = ModuleParameters(params=self.module.params)
2322 self.have = ApiParameters()
2323 self.changes = UsableChanges()
2324
2325 def _update_changed_options(self):
2326 diff = Difference(self.want, self.have)
2327 updatables = Parameters.updatables
2328 changed = dict()
2329 for k in updatables:
2330 change = diff.compare(k)
2331 if change is None:
2332 continue
2333 else:
2334 if isinstance(change, dict):
2335 changed.update(change)
2336 else:
2337 changed[k] = change
2338 if changed:
2339 self.changes = UsableChanges(params=changed)
2340 return True
2341 return False
2342
2343 def should_update(self):
2344 result = self._update_changed_options()
2345 if result:
2346 return True
2347 return False
2348
2349 def exec_module(self):
2350 start = datetime.now().isoformat()
2351 version = tmos_version(self.client)
2352 changed = False
2353 result = dict()
2354 state = self.want.state
2355
2356 if state == "present":
2357 changed = self.present()
2358 elif state == "absent":
2359 changed = self.absent()
2360 reportable = ReportableChanges(params=self.changes.to_return())
2361 changes = reportable.to_return()
2362 result.update(**changes)
2363 result.update(dict(changed=changed))
2364 self._announce_deprecations(result)
2365 send_teem(start, self.client, self.module, version)
2366 return result
2367
2368 def _announce_deprecations(self, result):
2369 warnings = result.pop('__warnings', [])
2370 for warning in warnings:
2371 self.module.deprecate(
2372 msg=warning['msg'],
2373 version=warning['version']
2374 )
2375
2376 def present(self):
2377 if self.exists():
2378 return self.update()
2379 else:
2380 return self.create()
2381
2382 def absent(self):
2383 if self.exists():
2384 return self.remove()
2385 return False
2386
2387 def update(self):
2388 self.have = self.read_current_from_device()
2389 if not self.should_update():
2390 return False
2391 if self.module.check_mode:
2392 return True
2393 if self.draft_exists():
2394 redraft = True
2395 else:
2396 redraft = False
2397 self._create_existing_policy_draft_on_device()
2398 self.update_on_device()
2399 if redraft is False:
2400 self.publish_on_device()
2401 return True
2402
2403 def remove(self):
2404 if self.module.check_mode:
2405 return True
2406 if self.draft_exists():
2407 redraft = True
2408 else:
2409 redraft = False
2410 self._create_existing_policy_draft_on_device()
2411 self.remove_from_device()
2412 if self.exists():
2413 raise F5ModuleError("Failed to delete the resource.")
2414 if redraft is False:
2415 self.publish_on_device()
2416 return True
2417
2418 def create(self):
2419 self.should_update()
2420 if self.module.check_mode:
2421 return True
2422 if self.draft_exists():
2423 redraft = True
2424 else:
2425 redraft = False
2426 self._create_existing_policy_draft_on_device()
2427 self.create_on_device()
2428 if redraft is False:
2429 self.publish_on_device()
2430 return True
2431
2432 def exists(self):
2433 if self.draft_exists():
2434 uri = "https://{0}:{1}/mgmt/tm/ltm/policy/{2}/rules/{3}".format(
2435 self.client.provider['server'],
2436 self.client.provider['server_port'],
2437 transform_name(self.want.partition, self.want.policy, sub_path='Drafts'),
2438 self.want.name
2439 )
2440 else:
2441 uri = "https://{0}:{1}/mgmt/tm/ltm/policy/{2}/rules/{3}".format(
2442 self.client.provider['server'],
2443 self.client.provider['server_port'],
2444 transform_name(self.want.partition, self.want.policy),
2445 self.want.name
2446 )
2447 resp = self.client.api.get(uri)
2448 try:
2449 response = resp.json()
2450 except ValueError as ex:
2451 raise F5ModuleError(str(ex))
2452
2453 if resp.status == 404 or 'code' in response and response['code'] == 404:
2454 return False
2455 if resp.status in [200, 201] or 'code' in response and response['code'] in [200, 201]:
2456 return True
2457
2458 errors = [401, 403, 409, 500, 501, 502, 503, 504]
2459
2460 if resp.status in errors or 'code' in response and response['code'] in errors:
2461 if 'message' in response:
2462 raise F5ModuleError(response['message'])
2463 else:
2464 raise F5ModuleError(resp.content)
2465
2466 def draft_exists(self):
2467 uri = "https://{0}:{1}/mgmt/tm/ltm/policy/{2}".format(
2468 self.client.provider['server'],
2469 self.client.provider['server_port'],
2470 transform_name(self.want.partition, self.want.policy, sub_path='Drafts')
2471 )
2472 resp = self.client.api.get(uri)
2473 try:
2474 response = resp.json()
2475 except ValueError as ex:
2476 raise F5ModuleError(str(ex))
2477
2478 if resp.status == 404 or 'code' in response and response['code'] == 404:
2479 return False
2480 if resp.status in [200, 201] or 'code' in response and response['code'] in [200, 201]:
2481 return True
2482
2483 errors = [401, 403, 409, 500, 501, 502, 503, 504]
2484
2485 if resp.status in errors or 'code' in response and response['code'] in errors:
2486 if 'message' in response:
2487 raise F5ModuleError(response['message'])
2488 else:
2489 raise F5ModuleError(resp.content)
2490
2491 def _create_existing_policy_draft_on_device(self):
2492 params = dict(createDraft=True)
2493 uri = "https://{0}:{1}/mgmt/tm/ltm/policy/{2}".format(
2494 self.client.provider['server'],
2495 self.client.provider['server_port'],
2496 transform_name(self.want.partition, self.want.policy)
2497 )
2498 resp = self.client.api.patch(uri, json=params)
2499 try:
2500 response = resp.json()
2501 except ValueError as ex:
2502 raise F5ModuleError(str(ex))
2503
2504 if resp.status in [200, 201] or 'code' in response and response['code'] in [200, 201]:
2505 return True
2506 raise F5ModuleError(resp.content)
2507
2508 def publish_on_device(self):
2509 params = dict(
2510 name=fq_name(self.want.partition,
2511 self.want.policy,
2512 sub_path='Drafts'
2513 ),
2514 command="publish"
2515
2516 )
2517 uri = "https://{0}:{1}/mgmt/tm/ltm/policy/".format(
2518 self.client.provider['server'],
2519 self.client.provider['server_port'],
2520 )
2521 resp = self.client.api.post(uri, json=params)
2522 try:
2523 response = resp.json()
2524 except ValueError as ex:
2525 raise F5ModuleError(str(ex))
2526
2527 if resp.status in [200, 201] or 'code' in response and response['code'] in [200, 201]:
2528 return True
2529 raise F5ModuleError(resp.content)
2530
2531 def create_on_device(self):
2532 params = self.changes.api_params()
2533 params['name'] = self.want.name
2534 uri = "https://{0}:{1}/mgmt/tm/ltm/policy/{2}/rules/".format(
2535 self.client.provider['server'],
2536 self.client.provider['server_port'],
2537 transform_name(self.want.partition, self.want.policy, sub_path='Drafts'),
2538 )
2539 resp = self.client.api.post(uri, json=params)
2540 try:
2541 response = resp.json()
2542 except ValueError as ex:
2543 raise F5ModuleError(str(ex))
2544
2545 if resp.status in [200, 201] or 'code' in response and response['code'] in [200, 201]:
2546 return True
2547 raise F5ModuleError(resp.content)
2548
2549 def update_on_device(self):
2550 params = self.changes.api_params()
2551 uri = "https://{0}:{1}/mgmt/tm/ltm/policy/{2}/rules/{3}".format(
2552 self.client.provider['server'],
2553 self.client.provider['server_port'],
2554 transform_name(self.want.partition, self.want.policy, sub_path='Drafts'),
2555 self.want.name
2556 )
2557 resp = self.client.api.patch(uri, json=params)
2558 try:
2559 response = resp.json()
2560 except ValueError as ex:
2561 raise F5ModuleError(str(ex))
2562
2563 if resp.status in [200, 201] or 'code' in response and response['code'] in [200, 201]:
2564 return True
2565 raise F5ModuleError(resp.content)
2566
2567 def remove_from_device(self):
2568 uri = "https://{0}:{1}/mgmt/tm/ltm/policy/{2}/rules/{3}".format(
2569 self.client.provider['server'],
2570 self.client.provider['server_port'],
2571 transform_name(self.want.partition, self.want.policy, sub_path='Drafts'),
2572 self.want.name
2573 )
2574 response = self.client.api.delete(uri)
2575 if response.status == 200:
2576 return True
2577 raise F5ModuleError(response.content)
2578
2579 def read_current_from_device(self):
2580 if self.draft_exists():
2581 uri = "https://{0}:{1}/mgmt/tm/ltm/policy/{2}/rules/{3}".format(
2582 self.client.provider['server'],
2583 self.client.provider['server_port'],
2584 transform_name(self.want.partition, self.want.policy, sub_path='Drafts'),
2585 self.want.name
2586 )
2587 else:
2588 uri = "https://{0}:{1}/mgmt/tm/ltm/policy/{2}/rules/{3}".format(
2589 self.client.provider['server'],
2590 self.client.provider['server_port'],
2591 transform_name(self.want.partition, self.want.policy),
2592 self.want.name
2593 )
2594 query = "?expandSubcollections=true"
2595 resp = self.client.api.get(uri + query)
2596 try:
2597 response = resp.json()
2598 except ValueError as ex:
2599 raise F5ModuleError(str(ex))
2600
2601 if resp.status in [200, 201] or 'code' in response and response['code'] in [200, 201]:
2602 return ApiParameters(params=response)
2603 raise F5ModuleError(resp.content)
2604
2605
2606 class ArgumentSpec(object):
2607 def __init__(self):
2608 self.supports_check_mode = True
2609 argument_spec = dict(
2610 description=dict(),
2611 actions=dict(
2612 type='list',
2613 elements='dict',
2614 options=dict(
2615 type=dict(
2616 choices=[
2617 'forward',
2618 'enable',
2619 'ignore',
2620 'redirect',
2621 'reset',
2622 'persist',
2623 'set_variable',
2624 'remove',
2625 'insert',
2626 'replace',
2627 'disable',
2628 ],
2629 required=True
2630 ),
2631 pool=dict(),
2632 node=dict(),
2633 asm_policy=dict(),
2634 virtual=dict(),
2635 location=dict(),
2636 event=dict(),
2637 cookie_insert=dict(),
2638 cookie_expiry=dict(type='int'),
2639 expression=dict(),
2640 variable_name=dict(),
2641 disable_target=dict(
2642 choices=['server_ssl', 'persist', 'asm']
2643 ),
2644 http_header=dict(
2645 type='dict',
2646 options=dict(
2647 event=dict(
2648 choices=[
2649 'request', 'response', 'proxy_connect',
2650 'proxy_request', 'proxy_response'
2651 ],
2652 required=True
2653 ),
2654 name=dict(required=True),
2655 value=dict()
2656 )
2657 ),
2658 http_referer=dict(
2659 type='dict',
2660 options=dict(
2661 event=dict(
2662 choices=['request', 'proxy_connect', 'proxy_request'],
2663 required=True
2664 ),
2665 value=dict()
2666 )
2667 ),
2668 http_set_cookie=dict(
2669 type='dict',
2670 options=dict(
2671 name=dict(required=True),
2672 value=dict()
2673 )
2674 ),
2675 http_cookie=dict(
2676 type='dict',
2677 options=dict(
2678 event=dict(
2679 choices=['request', 'proxy_connect', 'proxy_request'],
2680 required=True
2681
2682 ),
2683 name=dict(required=True),
2684 value=dict()
2685 )
2686 ),
2687 http_connect=dict(
2688 type='dict',
2689 options=dict(
2690 event=dict(
2691 choices=[
2692 'client_accepted', 'proxy_connect', 'proxy_request',
2693 'proxy_response', 'request', 'server_connected', 'ssl_client_hello'
2694 ],
2695 required=True
2696 ),
2697 value=dict(
2698 required=True
2699 ),
2700 port=dict(type='int'),
2701 )
2702 ),
2703 http_host=dict(
2704 type='dict',
2705 options=dict(
2706 event=dict(
2707 choices=['request', 'proxy_connect', 'proxy_request'],
2708 required=True
2709 ),
2710 value=dict(required=True)
2711 )
2712 ),
2713 http_uri=dict(
2714 type='dict',
2715 options=dict(
2716 event=dict(
2717 choices=['request', 'proxy_connect', 'proxy_request'],
2718 required=True
2719 ),
2720 type=dict(
2721 choices=['path', 'query_string', 'full_string'],
2722 required=True
2723 ),
2724 value=dict(required=True)
2725 ),
2726
2727 ),
2728 ),
2729 mutually_exclusive=[
2730 ['pool', 'asm_policy', 'virtual', 'location', 'cookie_insert', 'node', 'http_header',
2731 'http_referer', 'http_set_cookie', 'http_cookie', 'http_uri', 'http_host', 'http_connect',
2732 'disable_target'
2733 ]
2734 ]
2735 ),
2736 conditions=dict(
2737 type='list',
2738 elements='dict',
2739 options=dict(
2740 type=dict(
2741 choices=[
2742 'http_uri',
2743 'http_method',
2744 'http_host',
2745 'http_header',
2746 'ssl_extension',
2747 'all_traffic',
2748 'tcp'
2749 ],
2750 required=True
2751 ),
2752 path_begins_with_any=dict(
2753 type='list',
2754 elements='str',
2755 ),
2756 path_contains=dict(
2757 type='list',
2758 elements='str',
2759 ),
2760 path_is_any=dict(
2761 type='list',
2762 elements='str',
2763 ),
2764 host_begins_with_any=dict(
2765 type='list',
2766 elements='str',
2767 ),
2768 host_begins_not_with_any=dict(
2769 type='list',
2770 elements='str',
2771 ),
2772 host_ends_with_any=dict(
2773 type='list',
2774 elements='str',
2775 ),
2776 host_ends_not_with_any=dict(
2777 type='list',
2778 elements='str',
2779 ),
2780 host_is_any=dict(
2781 type='list',
2782 elements='str',
2783 ),
2784 host_is_not_any=dict(
2785 type='list',
2786 elements='str',
2787 ),
2788 host_contains=dict(
2789 type='list',
2790 elements='str',
2791 ),
2792 header_name=dict(),
2793 header_is_any=dict(
2794 type='list',
2795 elements='str',
2796 ),
2797 method_matches_with_any=dict(
2798 type='list',
2799 elements='str',
2800 ),
2801 server_name_is_any=dict(
2802 type='list',
2803 elements='str',
2804 ),
2805 server_name_is_not_any=dict(
2806 type='list',
2807 elements='str',
2808 ),
2809 server_name_begins_with_any=dict(
2810 type='list',
2811 elements='str',
2812 ),
2813 server_name_begins_not_with_any=dict(
2814 type='list',
2815 elements='str',
2816 ),
2817 server_name_ends_with_any=dict(
2818 type='list',
2819 elements='str',
2820 ),
2821 server_name_ends_not_with_any=dict(
2822 type='list',
2823 elements='str',
2824 ),
2825 server_name_contains=dict(
2826 type='list',
2827 elements='str',
2828 ),
2829 address_matches_with_any=dict(
2830 type='list',
2831 elements='str',
2832 ),
2833 address_matches_with_datagroup=dict(
2834 type='list',
2835 elements='str',
2836 ),
2837 address_matches_with_external_datagroup=dict(
2838 type='list',
2839 elements='str',
2840 ),
2841 event=dict()
2842 ),
2843 ),
2844 name=dict(required=True),
2845 policy=dict(required=True),
2846 rule_order=dict(type='int'),
2847 replace_with=dict(
2848 type='bool',
2849 default='no'
2850 ),
2851 state=dict(
2852 default='present',
2853 choices=['absent', 'present']
2854 ),
2855 partition=dict(
2856 default='Common',
2857 fallback=(env_fallback, ['F5_PARTITION'])
2858 )
2859 )
2860 self.argument_spec = {}
2861 self.argument_spec.update(f5_argument_spec)
2862 self.argument_spec.update(argument_spec)
2863
2864
2865 def main():
2866 spec = ArgumentSpec()
2867
2868 module = AnsibleModule(
2869 argument_spec=spec.argument_spec,
2870 supports_check_mode=spec.supports_check_mode
2871 )
2872
2873 try:
2874 mm = ModuleManager(module=module)
2875 results = mm.exec_module()
2876 module.exit_json(**results)
2877 except F5ModuleError as ex:
2878 module.fail_json(msg=str(ex))
2879
2880
2881 if __name__ == '__main__':
2882 main()