1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Copyright (c) 2017 F5 Networks Inc.
# GNU General Public License v3.0 (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'}
DOCUMENTATION = r'''
---
module: bigip_policy_rule
short_description: Manage LTM policy rules on a BIG-IP
description:
- This module will manage LTM policy rules on a BIG-IP.
version_added: 2.5
options:
description:
description:
- Description of the policy rule.
actions:
description:
- The actions that you want the policy rule to perform.
- The available attributes vary by the action, however, each action requires that
a C(type) be specified.
- These conditions can be specified in any order. Despite them being a list, the
BIG-IP does not treat their order as anything special.
- Available C(type) values are C(forward).
suboptions:
type:
description:
- The action type. This value controls what below options are required.
- When C(type) is C(forward), will associate a given C(pool) with this rule.
- When C(type) is C(enable), will associate a given C(asm_policy) with
this rule.
- When C(type) is C(ignore), will remove all existing actions from this
rule.
required: true
choices: ['forward', 'enable', 'ignore']
pool:
description:
- Pool that you want to forward traffic to.
- This parameter is only valid with the C(forward) type.
asm_policy:
description:
- ASM policy to enable.
- This parameter is only valid with the C(enable) type.
policy:
description:
- The name of the policy that you want to associate this rule with.
required: True
name:
description:
- The name of the rule.
required: True
conditions:
description:
- A list of attributes that describe the condition.
- See suboptions for details on how to construct each list entry.
- The ordering of this list is important, the module will ensure the order is
kept when modifying the task.
- The suboption options listed below are not required for all condition types,
read the description for more details.
- These conditions can be specified in any order. Despite them being a list, the
BIG-IP does not treat their order as anything special.
suboptions:
type:
description:
- The condition type. This value controls what below options are required.
- When C(type) is C(http_uri), will associate a given C(path_begins_with_any)
list of strings with which the HTTP URI should begin with. Any item in the
list will provide a match.
- When C(type) is C(all_traffic), will remove all existing conditions from
this rule.
required: True
choices: [ 'http_uri', 'all_traffic' ]
path_begins_with_any:
description:
- A list of strings of characters that the HTTP URI should start with.
- This parameter is only valid with the C(http_uri) type.
state:
description:
- When C(present), ensures that the key is uploaded to the device. When
C(absent), ensures that the key is removed from the device. If the key
is currently in use, the module will not be able to remove the key.
default: present
choices:
- present
- absent
partition:
description:
- Device partition to manage resources on.
default: Common
extends_documentation_fragment: f5
requirements:
- BIG-IP >= v12.1.0
author:
- Tim Rupp (@caphrim007)
'''
EXAMPLES = r'''
- name: Create policies
bigip_policy:
name: Policy-Foo
state: present
delegate_to: localhost
- name: Add a rule to the new policy
bigip_policy_rule:
policy: Policy-Foo
name: rule3
conditions:
- type: http_uri
path_begins_with_any: /ABC
actions:
- type: forward
pool: pool-svrs
delegate_to: localhost
- name: Add multiple rules to the new policy
bigip_policy_rule:
policy: Policy-Foo
name: "{{ item.name }}"
conditions: "{{ item.conditions }}"
actions: "{{ item.actions }}"
delegate_to: localhost
loop:
- name: rule1
actions:
- type: forward
pool: pool-svrs
conditions:
- type: http_uri
path_starts_with: /euro
- name: rule2
actions:
- type: forward
pool: pool-svrs
conditions:
- type: http_uri
path_starts_with: /HomePage/
- name: Remove all rules and confitions from the rule
bigip_policy_rule:
policy: Policy-Foo
name: rule1
conditions:
- type: all_traffic
actions:
- type: ignore
delegate_to: localhost
'''
RETURN = r'''
actions:
description: The new list of actions applied to the rule
returned: changed
type: complex
contains:
type:
description: The action type
returned: changed
type: string
sample: forward
pool:
description: Pool for forward to
returned: changed
type: string
sample: foo-pool
sample: hash/dictionary of values
conditions:
description: The new list of conditions applied to the rule.
returned: changed
type: complex
contains:
type:
description: The condition type
returned: changed
type: string
sample: http_uri
path_begins_with_any:
description: List of strings that the URI begins with.
returned: changed
type: list
sample: [foo, bar]
sample: hash/dictionary of values
description:
description: The new description of the rule.
returned: changed
type: string
sample: My rule
'''
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.basic import env_fallback
from ansible.module_utils.six import iteritems
try:
from library.module_utils.network.f5.bigip import HAS_F5SDK
from library.module_utils.network.f5.bigip import F5Client
from library.module_utils.network.f5.common import F5ModuleError
from library.module_utils.network.f5.common import AnsibleF5Parameters
from library.module_utils.network.f5.common import cleanup_tokens
from library.module_utils.network.f5.common import fq_name
from library.module_utils.network.f5.common import f5_argument_spec
try:
from library.module_utils.network.f5.common import iControlUnexpectedHTTPError
except ImportError:
HAS_F5SDK = False
except ImportError:
from ansible.module_utils.network.f5.bigip import HAS_F5SDK
from ansible.module_utils.network.f5.bigip import F5Client
from ansible.module_utils.network.f5.common import F5ModuleError
from ansible.module_utils.network.f5.common import AnsibleF5Parameters
from ansible.module_utils.network.f5.common import cleanup_tokens
from ansible.module_utils.network.f5.common import fq_name
from ansible.module_utils.network.f5.common import f5_argument_spec
try:
from ansible.module_utils.network.f5.common import iControlUnexpectedHTTPError
except ImportError:
HAS_F5SDK = False
class Parameters(AnsibleF5Parameters):
api_map = {
'actionsReference': 'actions',
'conditionsReference': 'conditions'
}
api_attributes = [
'description', 'actions', 'conditions'
]
updatables = [
'actions', 'conditions', 'description'
]
returnable = [
'description'
]
@property
def name(self):
return self._values.get('name', None)
@property
def description(self):
return self._values.get('description', None)
@property
def policy(self):
if self._values['policy'] is None:
return None
return self._values['policy']
class ApiParameters(Parameters):
def _remove_internal_keywords(self, resource):
items = ['kind', 'generation', 'selfLink', 'poolReference']
for item in items:
try:
del resource[item]
except KeyError:
pass
@property
def actions(self):
result = []
if self._values['actions'] is None or 'items' not in self._values['actions']:
return [dict(type='ignore')]
for item in self._values['actions']['items']:
action = dict()
self._remove_internal_keywords(item)
if 'forward' in item:
action.update(item)
action['type'] = 'forward'
del action['forward']
elif 'enable' in item:
action.update(item)
action['type'] = 'enable'
del action['enable']
result.append(action)
result = sorted(result, key=lambda x: x['name'])
return result
@property
def conditions(self):
result = []
if self._values['conditions'] is None or 'items' not in self._values['conditions']:
return [dict(type='all_traffic')]
for item in self._values['conditions']['items']:
action = dict()
self._remove_internal_keywords(item)
if 'httpUri' in item:
action.update(item)
action['type'] = 'http_uri'
del action['httpUri']
# Converts to common stringiness
#
# The tuple set "issubset" check that happens in the Difference
# engine does not recognize that a u'foo' and 'foo' are equal "enough"
# to consider them a subset. Therefore, we cast everything here to
# whatever the common stringiness is.
if 'values' in action:
action['values'] = [str(x) for x in action['values']]
result.append(action)
# Names contains the index in which the rule is at.
result = sorted(result, key=lambda x: x['name'])
return result
class ModuleParameters(Parameters):
@property
def actions(self):
result = []
if self._values['actions'] is None:
return None
for idx, item in enumerate(self._values['actions']):
action = dict()
if 'name' in item:
action['name'] = str(item['name'])
else:
action['name'] = str(idx)
if item['type'] == 'forward':
self._handle_forward_action(action, item)
elif item['type'] == 'enable':
self._handle_enable_action(action, item)
elif item['type'] == 'ignore':
return [dict(type='ignore')]
result.append(action)
result = sorted(result, key=lambda x: x['name'])
return result
@property
def conditions(self):
result = []
if self._values['conditions'] is None:
return None
for idx, item in enumerate(self._values['conditions']):
action = dict()
if 'name' in item:
action['name'] = str(item['name'])
else:
action['name'] = str(idx)
if item['type'] == 'http_uri':
self._handle_http_uri_condition(action, item)
elif item['type'] == 'all_traffic':
return [dict(type='all_traffic')]
result.append(action)
result = sorted(result, key=lambda x: x['name'])
return result
def _handle_http_uri_condition(self, action, item):
"""Handle the nuances of the forwarding type
Right now there is only a single type of forwarding that can be done. As that
functionality expands, so-to will the behavior of this, and other, methods.
Therefore, do not be surprised that the logic here is so rigid. It's deliberate.
:param action:
:param item:
:return:
"""
action['type'] = 'http_uri'
if 'path_begins_with_any' not in item:
raise F5ModuleError(
"A 'path_begins_with_any' must be specified when the 'http_uri' type is used."
)
if isinstance(item['path_begins_with_any'], list):
values = item['path_begins_with_any']
else:
values = [item['path_begins_with_any']]
action.update(dict(
path=True,
startsWith=True,
values=values
))
def _handle_forward_action(self, action, item):
"""Handle the nuances of the forwarding type
Right now there is only a single type of forwarding that can be done. As that
functionality expands, so-to will the behavior of this, and other, methods.
Therefore, do not be surprised that the logic here is so rigid. It's deliberate.
:param action:
:param item:
:return:
"""
action['type'] = 'forward'
if 'pool' not in item:
raise F5ModuleError(
"A 'pool' must be specified when the 'forward' type is used."
)
action['pool'] = fq_name(self.partition, item['pool'])
def _handle_enable_action(self, action, item):
"""Handle the nuances of the enable type
:param action:
:param item:
:return:
"""
action['type'] = 'enable'
if 'asm_policy' not in item:
raise F5ModuleError(
"An 'asm_policy' must be specified when the 'enable' type is used."
)
action.update(dict(
policy=fq_name(self.partition, item['asm_policy']),
asm=True
))
class Changes(Parameters):
def to_return(self):
result = {}
try:
for returnable in self.returnables:
result[returnable] = getattr(self, returnable)
result = self._filter_params(result)
except Exception:
pass
return result
class ReportableChanges(Changes):
returnables = [
'description', 'actions', 'conditions'
]
@property
def actions(self):
result = []
if self._values['actions'] is None:
return [dict(type='ignore')]
for item in self._values['actions']:
action = dict()
if 'forward' in item:
action.update(item)
action['type'] = 'forward'
del action['forward']
elif 'enable' in item:
action.update(item)
action['type'] = 'enable'
del action['enable']
result.append(action)
result = sorted(result, key=lambda x: x['name'])
return result
@property
def conditions(self):
result = []
if self._values['conditions'] is None:
return [dict(type='all_traffic')]
for item in self._values['conditions']:
action = dict()
if 'httpUri' in item:
action.update(item)
action['type'] = 'http_uri'
del action['httpUri']
result.append(action)
# Names contains the index in which the rule is at.
result = sorted(result, key=lambda x: x['name'])
return result
class UsableChanges(Changes):
@property
def actions(self):
if self._values['actions'] is None:
return None
result = []
for action in self._values['actions']:
if 'type' not in action:
continue
if action['type'] == 'forward':
action['forward'] = True
del action['type']
elif action['type'] == 'enable':
action['enable'] = True
del action['type']
elif action['type'] == 'ignore':
result = []
break
result.append(action)
return result
@property
def conditions(self):
if self._values['conditions'] is None:
return None
result = []
for condition in self._values['conditions']:
if 'type' not in condition:
continue
if condition['type'] == 'http_uri':
condition['httpUri'] = True
del condition['type']
elif condition['type'] == 'all_traffic':
result = []
break
result.append(condition)
return result
class Difference(object):
updatables = [
'actions', 'conditions', 'description'
]
def __init__(self, want, have=None):
self.want = want
self.have = have
def compare(self, param):
try:
result = getattr(self, param)
return result
except AttributeError:
return self.__default(param)
def __default(self, param):
attr1 = getattr(self.want, param)
try:
attr2 = getattr(self.have, param)
if attr1 != attr2:
return attr1
except AttributeError:
return attr1
def to_tuple(self, items):
result = []
for x in items:
tmp = [(str(k), str(v)) for k, v in iteritems(x)]
result += tmp
return result
def _diff_complex_items(self, want, have):
if want == [] and have is None:
return None
if want is None:
return None
w = self.to_tuple(want)
h = self.to_tuple(have)
if set(w).issubset(set(h)):
return None
else:
return want
@property
def actions(self):
result = self._diff_complex_items(self.want.actions, self.have.actions)
if self._conditions_missing_default_rule_for_asm(result):
raise F5ModuleError(
"The 'all_traffic' condition is required when using an ASM policy in a rule's 'enable' action."
)
return result
@property
def conditions(self):
result = self._diff_complex_items(self.want.conditions, self.have.conditions)
return result
def _conditions_missing_default_rule_for_asm(self, want_actions):
if want_actions is None:
actions = self.have.actions
else:
actions = want_actions
if actions is None:
return False
if any(x for x in actions if x['type'] == 'enable'):
conditions = self._diff_complex_items(self.want.conditions, self.have.conditions)
if conditions is None:
return False
if any(y for y in conditions if y['type'] != 'all_traffic'):
return True
return False
class ModuleManager(object):
def __init__(self, *args, **kwargs):
self.module = kwargs.get('module', None)
self.client = kwargs.get('client', None)
self.want = ModuleParameters(params=self.module.params)
self.have = ApiParameters()
self.changes = UsableChanges()
def _update_changed_options(self):
diff = Difference(self.want, self.have)
updatables = Parameters.updatables
changed = dict()
for k in updatables:
change = diff.compare(k)
if change is None:
continue
else:
if isinstance(change, dict):
changed.update(change)
else:
changed[k] = change
if changed:
self.changes = UsableChanges(params=changed)
return True
return False
def should_update(self):
result = self._update_changed_options()
if result:
return True
return False
def exec_module(self):
changed = False
result = dict()
state = self.want.state
try:
if state == "present":
changed = self.present()
elif state == "absent":
changed = self.absent()
except iControlUnexpectedHTTPError as e:
raise F5ModuleError(str(e))
reportable = ReportableChanges(params=self.changes.to_return())
changes = reportable.to_return()
result.update(**changes)
result.update(dict(changed=changed))
self._announce_deprecations(result)
return result
def _announce_deprecations(self, result):
warnings = result.pop('__warnings', [])
for warning in warnings:
self.module.deprecate(
msg=warning['msg'],
version=warning['version']
)
def present(self):
if self.exists():
return self.update()
else:
return self.create()
def exists(self):
args = dict(
name=self.want.policy,
partition=self.want.partition,
)
if self.draft_exists():
args['subPath'] = 'Drafts'
policy = self.client.api.tm.ltm.policys.policy.load(**args)
result = policy.rules_s.rules.exists(
name=self.want.name
)
return result
def draft_exists(self):
params = dict(
name=self.want.policy,
partition=self.want.partition,
subPath='Drafts'
)
result = self.client.api.tm.ltm.policys.policy.exists(**params)
return result
def _create_existing_policy_draft_on_device(self):
params = dict(
name=self.want.policy,
partition=self.want.partition,
)
resource = self.client.api.tm.ltm.policys.policy.load(**params)
resource.draft()
return True
def publish_on_device(self):
resource = self.client.api.tm.ltm.policys.policy.load(
name=self.want.policy,
partition=self.want.partition,
subPath='Drafts'
)
resource.publish()
return True
def update(self):
self.have = self.read_current_from_device()
if not self.should_update():
return False
if self.module.check_mode:
return True
if self.draft_exists():
redraft = True
else:
redraft = False
self._create_existing_policy_draft_on_device()
self.update_on_device()
if redraft is False:
self.publish_on_device()
return True
def remove(self):
if self.module.check_mode:
return True
if self.draft_exists():
redraft = True
else:
redraft = False
self._create_existing_policy_draft_on_device()
self.remove_from_device()
if self.exists():
raise F5ModuleError("Failed to delete the resource.")
if redraft is False:
self.publish_on_device()
return True
def create(self):
self.should_update()
if self.module.check_mode:
return True
if self.draft_exists():
redraft = True
else:
redraft = False
self._create_existing_policy_draft_on_device()
self.create_on_device()
if redraft is False:
self.publish_on_device()
return True
def create_on_device(self):
params = self.changes.api_params()
policy = self.client.api.tm.ltm.policys.policy.load(
name=self.want.policy,
partition=self.want.partition,
subPath='Drafts'
)
policy.rules_s.rules.create(
name=self.want.name,
**params
)
def update_on_device(self):
params = self.changes.api_params()
policy = self.client.api.tm.ltm.policys.policy.load(
name=self.want.policy,
partition=self.want.partition,
subPath='Drafts'
)
resource = policy.rules_s.rules.load(
name=self.want.name
)
resource.modify(**params)
def absent(self):
if self.exists():
return self.remove()
return False
def remove_from_device(self):
policy = self.client.api.tm.ltm.policys.policy.load(
name=self.want.policy,
partition=self.want.partition,
subPath='Drafts'
)
resource = policy.rules_s.rules.load(
name=self.want.name
)
if resource:
resource.delete()
def read_current_from_device(self):
args = dict(
name=self.want.policy,
partition=self.want.partition,
)
if self.draft_exists():
args['subPath'] = 'Drafts'
policy = self.client.api.tm.ltm.policys.policy.load(**args)
resource = policy.rules_s.rules.load(
name=self.want.name,
requests_params=dict(
params='expandSubcollections=true'
)
)
return ApiParameters(params=resource.attrs)
class ArgumentSpec(object):
def __init__(self):
self.supports_check_mode = True
argument_spec = dict(
description=dict(),
actions=dict(
type='list',
elements='dict',
options=dict(
type=dict(
choices=[
'forward',
'enable',
'ignore'
],
required=True
),
pool=dict(),
asm_policy=dict()
),
mutually_exclusive=[
['pool', 'asm_policy']
]
),
conditions=dict(
type='list',
options=dict(
type=dict(
choices=[
'http_uri',
'all_traffic'
],
required=True
),
path_begins_with_any=dict()
),
),
name=dict(required=True),
policy=dict(required=True),
state=dict(
default='present',
choices=['absent', 'present']
),
partition=dict(
default='Common',
fallback=(env_fallback, ['F5_PARTITION'])
)
)
self.argument_spec = {}
self.argument_spec.update(f5_argument_spec)
self.argument_spec.update(argument_spec)
def main():
spec = ArgumentSpec()
module = AnsibleModule(
argument_spec=spec.argument_spec,
supports_check_mode=spec.supports_check_mode
)
if not HAS_F5SDK:
module.fail_json(msg="The python f5-sdk module is required")
try:
client = F5Client(**module.params)
mm = ModuleManager(module=module, client=client)
results = mm.exec_module()
cleanup_tokens(client)
module.exit_json(**results)
except F5ModuleError as ex:
cleanup_tokens(client)
module.fail_json(msg=str(ex))
if __name__ == '__main__':
main()
|