Debian Codegraph @

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

raw symbols SCIP
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3 #
4 # Copyright: (c) 2018, F5 Networks Inc.
5 # GNU General Public License v3.0 (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
6
7 from __future__ import absolute_import, division, print_function
8 __metaclass__ = type
9
10 DOCUMENTATION = r'''
11 ---
12 module: bigip_asm_policy_manage
13 short_description: Manage BIG-IP ASM policies
14 description:
15 - Manage BIG-IP ASM policies, create policies from templates, and manage global policy settings.
16 version_added: "1.0.0"
17 options:
18 active:
19 description:
20 - If C(true), applies and activates the existing inactive policy. If C(false), it
21 deactivates the existing active policy. Generally should be C(true) only in cases where
22 you want to activate new or existing policy.
23 - In TMOS v14 and later, deactivating the policy causes it to be detached from any other associated objects,
24 therefore the default option of C(false) has been removed in order to prevent accidental disassociation.
25 type: bool
26 apply:
27 description:
28 - If C(true) applies the policy if the policy has pending changes.
29 - This parameter supported on TMOS C(v14.x) and above.
30 type: bool
31 version_added: "1.4.0"
32 name:
33 description:
34 - The ASM policy to manage or create.
35 type: str
36 required: True
37 state:
38 description:
39 - When C(state) is C(present), and the C(template) parameter is provided,
40 a new ASM policy is created from the template with the given policy C(name).
41 - When C(state) is C(present) and no C(template) parameter is provided, a
42 new blank ASM policy is created with the given policy C(name).
43 - When C(state) is C(absent), ensures the policy is removed, even if it is
44 currently active.
45 type: str
46 choices:
47 - present
48 - absent
49 default: present
50 template:
51 description:
52 - An ASM policy built-in template. If the template does not exist, an error is raised.
53 - Once the policy has been created, this value cannot change.
54 - The C(Comprehensive), C(Drupal), C(Fundamental), C(Joomla),
55 C(Vulnerability Assessment Baseline), and C(Wordpress) templates are only available
56 on BIG-IP versions >= 13.
57 type: str
58 choices:
59 - ActiveSync v1.0 v2.0 (http)
60 - ActiveSync v1.0 v2.0 (https)
61 - Comprehensive
62 - Drupal
63 - Fundamental
64 - Joomla
65 - LotusDomino 6.5 (http)
66 - LotusDomino 6.5 (https)
67 - OWA Exchange 2003 (http)
68 - OWA Exchange 2003 (https)
69 - OWA Exchange 2003 with ActiveSync (http)
70 - OWA Exchange 2003 with ActiveSync (https)
71 - OWA Exchange 2007 (http)
72 - OWA Exchange 2007 (https)
73 - OWA Exchange 2007 with ActiveSync (http)
74 - OWA Exchange 2007 with ActiveSync (https)
75 - OWA Exchange 2010 (http)
76 - OWA Exchange 2010 (https)
77 - Oracle 10g Portal (http)
78 - Oracle 10g Portal (https)
79 - Oracle Applications 11i (http)
80 - Oracle Applications 11i (https)
81 - PeopleSoft Portal 9 (http)
82 - PeopleSoft Portal 9 (https)
83 - Rapid Deployment Policy
84 - SAP NetWeaver 7 (http)
85 - SAP NetWeaver 7 (https)
86 - SharePoint 2003 (http)
87 - SharePoint 2003 (https)
88 - SharePoint 2007 (http)
89 - SharePoint 2007 (https)
90 - SharePoint 2010 (http)
91 - SharePoint 2010 (https)
92 - Vulnerability Assessment Baseline
93 - Wordpress
94 partition:
95 description:
96 - Device partition to manage resources on.
97 type: str
98 default: Common
99 extends_documentation_fragment: f5networks.f5_modules.f5
100 author:
101 - Wojciech Wypior (@wojtek0806)
102 '''
103
104 EXAMPLES = r'''
105 - name: Create ASM policy from template
106 bigip_asm_policy:
107 name: new_sharepoint_policy
108 template: SharePoint 2007 (http)
109 state: present
110 provider:
111 server: lb.mydomain.com
112 user: admin
113 password: secret
114 delegate_to: localhost
115
116 - name: Create blank ASM policy
117 bigip_asm_policy:
118 name: new_blank_policy
119 state: present
120 provider:
121 server: lb.mydomain.com
122 user: admin
123 password: secret
124 delegate_to: localhost
125
126 - name: Create blank ASM policy and activate
127 bigip_asm_policy_manage:
128 name: new_blank_policy
129 active: true
130 state: present
131 provider:
132 server: lb.mydomain.com
133 user: admin
134 password: secret
135 delegate_to: localhost
136
137 - name: Activate ASM policy
138 bigip_asm_policy_manage:
139 name: inactive_policy
140 active: true
141 state: present
142 provider:
143 server: lb.mydomain.com
144 user: admin
145 password: secret
146 delegate_to: localhost
147
148 - name: Deactivate ASM policy
149 bigip_asm_policy_manage:
150 name: active_policy
151 state: present
152 provider:
153 server: lb.mydomain.com
154 user: admin
155 password: secret
156 delegate_to: localhost
157 '''
158
159 RETURN = r'''
160 active:
161 description: Set when activating/deactivating an ASM policy.
162 returned: changed
163 type: bool
164 sample: true
165 apply:
166 description: Set when applying pending changes to an ASM policy.
167 returned: changed when target policy has changes pending
168 type: bool
169 sample: true
170 state:
171 description: Action performed on the target device.
172 returned: changed
173 type: str
174 sample: absent
175 template:
176 description: Name of the built-in ASM policy template.
177 returned: changed
178 type: str
179 sample: OWA Exchange 2007 (https)
180 name:
181 description: Name of the ASM policy to be managed/created.
182 returned: changed
183 type: str
184 sample: Asm_APP1_Transparent
185 '''
186
187 import time
188 import traceback
189 from datetime import datetime
190
191 try:
192 from packaging.version import Version
193 except ImportError:
194 HAS_PACKAGING = False
195 Version = None
196 PACKAGING_IMPORT_ERROR = traceback.format_exc()
197 else:
198 HAS_PACKAGING = True
199 PACKAGING_IMPORT_ERROR = None
200
201 from ansible.module_utils.basic import (
202 AnsibleModule, env_fallback, missing_required_lib
203 )
204
205 from ..module_utils.bigip import F5RestClient
206 from ..module_utils.common import (
207 F5ModuleError, AnsibleF5Parameters, f5_argument_spec, flatten_boolean, fq_name
208 )
209 from ..module_utils.icontrol import (
210 module_provisioned, tmos_version
211 )
212 from ..module_utils.teem import send_teem
213
214
215 class Parameters(AnsibleF5Parameters):
216 updatables = [
217 'active',
218 'apply',
219 ]
220
221 returnables = [
222 'name',
223 'template',
224 'active',
225 'apply',
226 ]
227
228 api_attributes = []
229 api_map = {
230 'isModified': 'apply'
231 }
232
233 @property
234 def template_link(self):
235 if self._values['template_link'] is not None:
236 return self._values['template_link']
237
238 result = None
239
240 uri = "https://{0}:{1}/mgmt/tm/asm/policy-templates/".format(
241 self.client.provider['server'],
242 self.client.provider['server_port'],
243 )
244
245 query = "?$filter=name+eq+{0}".format(self.template.upper())
246 resp = self.client.api.get(uri + query)
247
248 try:
249 response = resp.json()
250 except ValueError as ex:
251 raise F5ModuleError(str(ex))
252
253 if resp.status not in [200, 201] or 'code' in response and response['code'] not in [200, 201]:
254 raise F5ModuleError(resp.content)
255
256 if 'items' in response and response['items'] != []:
257 result = dict(link=response['items'][0]['selfLink'])
258
259 return result
260
261 @property
262 def active(self):
263 result = flatten_boolean(self._values['active'])
264 if result is None:
265 return None
266 if result == 'yes':
267 return True
268 return False
269
270
271 class V1ModuleParameters(Parameters):
272 @property
273 def template(self):
274 if self._values['template'] is None:
275 return None
276 template_map = {
277 'ActiveSync v1.0 v2.0 (http)': 'POLICY_TEMPLATE_ACTIVESYNC_V1_0_V2_0_HTTP',
278 'ActiveSync v1.0 v2.0 (https)': 'POLICY_TEMPLATE_ACTIVESYNC_V1_0_V2_0_HTTPS',
279 'LotusDomino 6.5 (http)': 'POLICY_TEMPLATE_LOTUSDOMINO_6_5_HTTP',
280 'LotusDomino 6.5 (https)': 'POLICY_TEMPLATE_LOTUSDOMINO_6_5_HTTPS',
281 'OWA Exchange 2003 (http)': 'POLICY_TEMPLATE_OWA_EXCHANGE_2003_HTTP',
282 'OWA Exchange 2003 (https)': 'POLICY_TEMPLATE_OWA_EXCHANGE_2003_HTTPS',
283 'OWA Exchange 2003 with ActiveSync (http)': 'POLICY_TEMPLATE_OWA_EXCHANGE_2003_WITH_ACTIVESYNC_HTTP',
284 'OWA Exchange 2003 with ActiveSync (https)': 'POLICY_TEMPLATE_OWA_EXCHANGE_2003_WITH_ACTIVESYNC_HTTPS',
285 'OWA Exchange 2007 (http)': 'POLICY_TEMPLATE_OWA_EXCHANGE_2007_HTTP',
286 'OWA Exchange 2007 (https)': 'POLICY_TEMPLATE_OWA_EXCHANGE_2007_HTTPS',
287 'OWA Exchange 2007 with ActiveSync (http)': 'POLICY_TEMPLATE_OWA_EXCHANGE_2007_WITH_ACTIVESYNC_HTTP',
288 'OWA Exchange 2007 with ActiveSync (https)': 'POLICY_TEMPLATE_OWA_EXCHANGE_2007_WITH_ACTIVESYNC_HTTPS',
289 'OWA Exchange 2010 (http)': 'POLICY_TEMPLATE_OWA_EXCHANGE_2010_HTTP',
290 'OWA Exchange 2010 (https)': 'POLICY_TEMPLATE_OWA_EXCHANGE_2010_HTTPS',
291 'Oracle 10g Portal (http)': 'POLICY_TEMPLATE_ORACLE_10G_PORTAL_HTTP',
292 'Oracle 10g Portal (https)': 'POLICY_TEMPLATE_ORACLE_10G_PORTAL_HTTPS',
293 'Oracle Applications 11i (http)': 'POLICY_TEMPLATE_ORACLE_APPLICATIONS_11I_HTTP',
294 'Oracle Applications 11i (https)': 'POLICY_TEMPLATE_ORACLE_APPLICATIONS_11I_HTTPS',
295 'PeopleSoft Portal 9 (http)': 'POLICY_TEMPLATE_PEOPLESOFT_PORTAL_9_HTTP',
296 'PeopleSoft Portal 9 (https)': 'POLICY_TEMPLATE_PEOPLESOFT_PORTAL_9_HTTPS',
297 'Rapid Deployment Policy': 'POLICY_TEMPLATE_RAPID_DEPLOYMENT',
298 'SAP NetWeaver 7 (http)': 'POLICY_TEMPLATE_SAP_NETWEAVER_7_HTTP',
299 'SAP NetWeaver 7 (https)': 'POLICY_TEMPLATE_SAP_NETWEAVER_7_HTTPS',
300 'SharePoint 2003 (http)': 'POLICY_TEMPLATE_SHAREPOINT_2003_HTTP',
301 'SharePoint 2003 (https)': 'POLICY_TEMPLATE_SHAREPOINT_2003_HTTPS',
302 'SharePoint 2007 (http)': 'POLICY_TEMPLATE_SHAREPOINT_2007_HTTP',
303 'SharePoint 2007 (https)': 'POLICY_TEMPLATE_SHAREPOINT_2007_HTTPS',
304 'SharePoint 2010 (http)': 'POLICY_TEMPLATE_SHAREPOINT_2010_HTTP',
305 'SharePoint 2010 (https)': 'POLICY_TEMPLATE_SHAREPOINT_2010_HTTPS'
306 }
307 if self._values['template'] in template_map:
308 return template_map[self._values['template']]
309 else:
310 raise F5ModuleError(
311 "The specified template is not valid for this version of BIG-IP."
312 )
313
314 @property
315 def apply(self):
316 result = flatten_boolean(self._values['apply'])
317 if result is None:
318 return None
319 if result == 'yes':
320 return True
321 return False
322
323
324 class V2ModuleParameters(Parameters):
325 @property
326 def template(self):
327 if self._values['template'] is None:
328 return None
329 template_map = {
330 'ActiveSync v1.0 v2.0 (http)': 'POLICY_TEMPLATE_ACTIVESYNC_V1_0_V2_0_HTTP',
331 'ActiveSync v1.0 v2.0 (https)': 'POLICY_TEMPLATE_ACTIVESYNC_V1_0_V2_0_HTTPS',
332 'Comprehensive': 'POLICY_TEMPLATE_COMPREHENSIVE', # v13
333 'Drupal': 'POLICY_TEMPLATE_DRUPAL', # v13
334 'Fundamental': 'POLICY_TEMPLATE_FUNDAMENTAL', # v13
335 'Joomla': 'POLICY_TEMPLATE_JOOMLA', # v13
336 'LotusDomino 6.5 (http)': 'POLICY_TEMPLATE_LOTUSDOMINO_6_5_HTTP',
337 'LotusDomino 6.5 (https)': 'POLICY_TEMPLATE_LOTUSDOMINO_6_5_HTTPS',
338 'OWA Exchange 2003 (http)': 'POLICY_TEMPLATE_OWA_EXCHANGE_2003_HTTP',
339 'OWA Exchange 2003 (https)': 'POLICY_TEMPLATE_OWA_EXCHANGE_2003_HTTPS',
340 'OWA Exchange 2003 with ActiveSync (http)': 'POLICY_TEMPLATE_OWA_EXCHANGE_2003_WITH_ACTIVESYNC_HTTP',
341 'OWA Exchange 2003 with ActiveSync (https)': 'POLICY_TEMPLATE_OWA_EXCHANGE_2003_WITH_ACTIVESYNC_HTTPS',
342 'OWA Exchange 2007 (http)': 'POLICY_TEMPLATE_OWA_EXCHANGE_2007_HTTP',
343 'OWA Exchange 2007 (https)': 'POLICY_TEMPLATE_OWA_EXCHANGE_2007_HTTPS',
344 'OWA Exchange 2007 with ActiveSync (http)': 'POLICY_TEMPLATE_OWA_EXCHANGE_2007_WITH_ACTIVESYNC_HTTP',
345 'OWA Exchange 2007 with ActiveSync (https)': 'POLICY_TEMPLATE_OWA_EXCHANGE_2007_WITH_ACTIVESYNC_HTTPS',
346 'OWA Exchange 2010 (http)': 'POLICY_TEMPLATE_OWA_EXCHANGE_2010_HTTP',
347 'OWA Exchange 2010 (https)': 'POLICY_TEMPLATE_OWA_EXCHANGE_2010_HTTPS',
348 'Oracle 10g Portal (http)': 'POLICY_TEMPLATE_ORACLE_10G_PORTAL_HTTP',
349 'Oracle 10g Portal (https)': 'POLICY_TEMPLATE_ORACLE_10G_PORTAL_HTTPS',
350 'Oracle Applications 11i (http)': 'POLICY_TEMPLATE_ORACLE_APPLICATIONS_11I_HTTP',
351 'Oracle Applications 11i (https)': 'POLICY_TEMPLATE_ORACLE_APPLICATIONS_11I_HTTPS',
352 'PeopleSoft Portal 9 (http)': 'POLICY_TEMPLATE_PEOPLESOFT_PORTAL_9_HTTP',
353 'PeopleSoft Portal 9 (https)': 'POLICY_TEMPLATE_PEOPLESOFT_PORTAL_9_HTTPS',
354 'Rapid Deployment Policy': 'POLICY_TEMPLATE_RAPID_DEPLOYMENT',
355 'SAP NetWeaver 7 (http)': 'POLICY_TEMPLATE_SAP_NETWEAVER_7_HTTP',
356 'SAP NetWeaver 7 (https)': 'POLICY_TEMPLATE_SAP_NETWEAVER_7_HTTPS',
357 'SharePoint 2003 (http)': 'POLICY_TEMPLATE_SHAREPOINT_2003_HTTP',
358 'SharePoint 2003 (https)': 'POLICY_TEMPLATE_SHAREPOINT_2003_HTTPS',
359 'SharePoint 2007 (http)': 'POLICY_TEMPLATE_SHAREPOINT_2007_HTTP',
360 'SharePoint 2007 (https)': 'POLICY_TEMPLATE_SHAREPOINT_2007_HTTPS',
361 'SharePoint 2010 (http)': 'POLICY_TEMPLATE_SHAREPOINT_2010_HTTP',
362 'SharePoint 2010 (https)': 'POLICY_TEMPLATE_SHAREPOINT_2010_HTTPS',
363 'Vulnerability Assessment Baseline': 'POLICY_TEMPLATE_VULNERABILITY_ASSESSMENT', # v13
364 'Wordpress': 'POLICY_TEMPLATE_WORDPRESS' # v13
365 }
366 return template_map[self._values['template']]
367
368 @property
369 def apply(self):
370 result = flatten_boolean(self._values['apply'])
371 if result is None:
372 return None
373 if result == 'yes':
374 return True
375 return False
376
377
378 class Changes(Parameters):
379 def to_return(self):
380 result = {}
381 try:
382 for returnable in self.returnables:
383 result[returnable] = getattr(self, returnable)
384 result = self._filter_params(result)
385 except Exception:
386 raise
387 return result
388
389
390 class UsableChanges(Changes):
391 pass
392
393
394 class ReportableChanges(Changes):
395 @property
396 def template(self):
397 if self._values['template'] is None:
398 return None
399 template_map = {
400 'POLICY_TEMPLATE_ACTIVESYNC_V1_0_V2_0_HTTP': 'ActiveSync v1.0 v2.0 (http)',
401 'POLICY_TEMPLATE_ACTIVESYNC_V1_0_V2_0_HTTPS': 'ActiveSync v1.0 v2.0 (https)',
402 'POLICY_TEMPLATE_COMPREHENSIVE': 'Comprehensive',
403 'POLICY_TEMPLATE_DRUPAL': 'Drupal',
404 'POLICY_TEMPLATE_FUNDAMENTAL': 'Fundamental',
405 'POLICY_TEMPLATE_JOOMLA': 'Joomla',
406 'POLICY_TEMPLATE_LOTUSDOMINO_6_5_HTTP': 'LotusDomino 6.5 (http)',
407 'POLICY_TEMPLATE_LOTUSDOMINO_6_5_HTTPS': 'LotusDomino 6.5 (https)',
408 'POLICY_TEMPLATE_OWA_EXCHANGE_2003_HTTP': 'OWA Exchange 2003 (http)',
409 'POLICY_TEMPLATE_OWA_EXCHANGE_2003_HTTPS': 'OWA Exchange 2003 (https)',
410 'POLICY_TEMPLATE_OWA_EXCHANGE_2003_WITH_ACTIVESYNC_HTTP': 'OWA Exchange 2003 with ActiveSync (http)',
411 'POLICY_TEMPLATE_OWA_EXCHANGE_2003_WITH_ACTIVESYNC_HTTPS': 'OWA Exchange 2003 with ActiveSync (https)',
412 'POLICY_TEMPLATE_OWA_EXCHANGE_2007_HTTP': 'OWA Exchange 2007 (http)',
413 'POLICY_TEMPLATE_OWA_EXCHANGE_2007_HTTPS': 'OWA Exchange 2007 (https)',
414 'POLICY_TEMPLATE_OWA_EXCHANGE_2007_WITH_ACTIVESYNC_HTTP': 'OWA Exchange 2007 with ActiveSync (http)',
415 'POLICY_TEMPLATE_OWA_EXCHANGE_2007_WITH_ACTIVESYNC_HTTPS': 'OWA Exchange 2007 with ActiveSync (https)',
416 'POLICY_TEMPLATE_OWA_EXCHANGE_2010_HTTP': 'OWA Exchange 2010 (http)',
417 'POLICY_TEMPLATE_OWA_EXCHANGE_2010_HTTPS': 'OWA Exchange 2010 (https)',
418 'POLICY_TEMPLATE_ORACLE_10G_PORTAL_HTTP': 'Oracle 10g Portal (http)',
419 'POLICY_TEMPLATE_ORACLE_10G_PORTAL_HTTPS': 'Oracle 10g Portal (https)',
420 'POLICY_TEMPLATE_ORACLE_APPLICATIONS_11I_HTTP': 'Oracle Applications 11i (http)',
421 'POLICY_TEMPLATE_ORACLE_APPLICATIONS_11I_HTTPS': 'Oracle Applications 11i (https)',
422 'POLICY_TEMPLATE_PEOPLESOFT_PORTAL_9_HTTP': 'PeopleSoft Portal 9 (http)',
423 'POLICY_TEMPLATE_PEOPLESOFT_PORTAL_9_HTTPS': 'PeopleSoft Portal 9 (https)',
424 'POLICY_TEMPLATE_RAPID_DEPLOYMENT': 'Rapid Deployment Policy',
425 'POLICY_TEMPLATE_SAP_NETWEAVER_7_HTTP': 'SAP NetWeaver 7 (http)',
426 'POLICY_TEMPLATE_SAP_NETWEAVER_7_HTTPS': 'SAP NetWeaver 7 (https)',
427 'POLICY_TEMPLATE_SHAREPOINT_2003_HTTP': 'SharePoint 2003 (http)',
428 'POLICY_TEMPLATE_SHAREPOINT_2003_HTTPS': 'SharePoint 2003 (https)',
429 'POLICY_TEMPLATE_SHAREPOINT_2007_HTTP': 'SharePoint 2007 (http)',
430 'POLICY_TEMPLATE_SHAREPOINT_2007_HTTPS': 'SharePoint 2007 (https)',
431 'POLICY_TEMPLATE_SHAREPOINT_2010_HTTP': 'SharePoint 2010 (http)',
432 'POLICY_TEMPLATE_SHAREPOINT_2010_HTTPS': 'SharePoint 2010 (https)',
433 'POLICY_TEMPLATE_VULNERABILITY_ASSESSMENT': 'Vulnerability Assessment Baseline',
434 'POLICY_TEMPLATE_WORDPRESS': 'Wordpress',
435 }
436 return template_map[self._values['template']]
437
438 @property
439 def apply(self):
440 result = flatten_boolean(self._values['apply'])
441 return result
442
443 @property
444 def active(self):
445 result = flatten_boolean(self._values['active'])
446 return result
447
448
449 class Difference(object):
450 def __init__(self, want, have=None):
451 self.want = want
452 self.have = have
453
454 def compare(self, param):
455 try:
456 result = getattr(self, param)
457 return result
458 except AttributeError:
459 return self.__default(param)
460
461 def __default(self, param):
462 attr1 = getattr(self.want, param)
463 try:
464 attr2 = getattr(self.have, param)
465 if attr1 != attr2:
466 return attr1
467 except AttributeError:
468 return attr1
469
470 @property
471 def active(self):
472 if self.want.active is None:
473 return None
474 if self.want.active is True and self.have.active is False:
475 return True
476 if self.want.active is False and self.have.active is True:
477 return False
478
479 @property
480 def apply(self):
481 if self.want.apply is True and self.have.apply is True:
482 return True
483
484
485 class BaseManager(object):
486 def __init__(self, *args, **kwargs):
487 self.client = kwargs.get('client', None)
488 self.module = kwargs.get('module', None)
489 self.have = None
490 self.changes = UsableChanges()
491
492 def exec_module(self):
493 start = datetime.now().isoformat()
494 version = tmos_version(self.client)
495 changed = False
496 result = dict()
497 state = self.want.state
498
499 if state == "present":
500 changed = self.present()
501 elif state == "absent":
502 changed = self.absent()
503
504 reportable = ReportableChanges(params=self.changes.to_return())
505 changes = reportable.to_return()
506 result.update(**changes)
507 result.update(dict(changed=changed))
508 self._announce_deprecations(result)
509 send_teem(start, self.client, self.module, version)
510 return result
511
512 def _announce_deprecations(self, result):
513 warnings = result.pop('__warnings', [])
514 for warning in warnings:
515 self.client.module.deprecate(
516 msg=warning['msg'],
517 version=warning['version']
518 )
519
520 def _set_changed_options(self):
521 changed = {}
522 for key in Parameters.returnables:
523 if getattr(self.want, key) is not None:
524 changed[key] = getattr(self.want, key)
525 if changed:
526 self.changes = UsableChanges(params=changed)
527
528 def should_update(self):
529 result = self._update_changed_options()
530 if result:
531 return True
532 return False
533
534 def _update_changed_options(self):
535 diff = Difference(self.want, self.have)
536 updatables = Parameters.updatables
537 changed = dict()
538 for k in updatables:
539 change = diff.compare(k)
540 if change is None:
541 continue
542 else:
543 if isinstance(change, dict):
544 changed.update(change)
545 else:
546 changed[k] = change
547 if changed:
548 self.changes = UsableChanges(params=changed)
549 return True
550 return False
551
552 def present(self):
553 if self.exists():
554 return self.update()
555 else:
556 return self.create()
557
558 def absent(self):
559 if not self.exists():
560 return False
561 else:
562 return self.remove()
563
564 def create(self):
565 self._set_changed_options()
566 if self.module.check_mode:
567 return True
568 if self.want.template is not None:
569 self.create_from_template()
570 if self.want.template is None:
571 self.create_blank()
572 if self.want.active:
573 self.activate()
574 return True
575 else:
576 return True
577
578 def update(self):
579 self.have = self.read_current_from_device()
580 if not self.should_update():
581 return False
582 if self.module.check_mode:
583 return True
584 self.update_on_device()
585 if self.changes.active or self.changes.apply:
586 self.activate()
587 return True
588
589 def activate(self):
590 if not self.have:
591 self.have = self.read_current_from_device()
592 task_id = self.apply_on_device()
593 if self.wait_for_task(task_id):
594 self.wait_for_policy_apply()
595 return True
596 else:
597 raise F5ModuleError('Apply policy task failed.')
598
599 def create_blank(self):
600 self.create_on_device()
601 if self.exists():
602 return True
603 else:
604 raise F5ModuleError(
605 'Failed to create ASM policy: {0}'.format(self.want.name)
606 )
607
608 def remove(self):
609 if self.module.check_mode:
610 return True
611 self.remove_from_device()
612 if self.exists():
613 raise F5ModuleError(
614 'Failed to delete ASM policy: {0}'.format(self.want.name)
615 )
616 return True
617
618 def exists(self):
619 uri = 'https://{0}:{1}/mgmt/tm/asm/policies/'.format(
620 self.client.provider['server'],
621 self.client.provider['server_port'],
622 )
623
624 query = "?$filter=contains(name,'{0}')+and+contains(partition,'{1}')&$select=name,partition".format(
625 self.want.name, self.want.partition
626 )
627 resp = self.client.api.get(uri + query)
628
629 try:
630 response = resp.json()
631 except ValueError as ex:
632 raise F5ModuleError(str(ex))
633
634 errors = [401, 403, 409, 500, 501, 502, 503, 504]
635
636 if resp.status in errors or 'code' in response and response['code'] in errors:
637 if 'message' in response:
638 raise F5ModuleError(response['message'])
639 else:
640 raise F5ModuleError(resp.content)
641 if 'items' in response and response['items'] != []:
642 # because api filter on ASM is broken when names that contain numbers at the end we need to work around it
643 for policy in response['items']:
644 if policy['name'] == self.want.name and policy['partition'] == self.want.partition:
645 return True
646 return False
647
648 def wait_for_policy_apply(self):
649 """
650 As the API is quite buggy and unstable there are cases where the policy still indicates pending changes
651 even after the apply-policy task has finished. Such state usually goes away after few seconds,
652 this function waits for the policy to achieve such a state for
653 maximum of 60 seconds.
654
655 """
656 # timer is required so that the api updates isModified state to a correct value.
657 time.sleep(3)
658 for x in range(0, 30):
659 self.have = self.read_current_from_device()
660 if self.have.apply is False:
661 break
662 time.sleep(2)
663 return True
664
665 def wait_for_task(self, task_id):
666 uri = "https://{0}:{1}/mgmt/tm/asm/tasks/apply-policy/{2}".format(
667 self.client.provider['server'],
668 self.client.provider['server_port'],
669 task_id
670 )
671 while True:
672 resp = self.client.api.get(uri)
673
674 try:
675 response = resp.json()
676 except ValueError as ex:
677 raise F5ModuleError(str(ex))
678
679 if resp.status not in [200, 201] or 'code' in response and response['code'] not in [200, 201]:
680 raise F5ModuleError(resp.content)
681
682 if response['status'] in ['COMPLETED', 'FAILURE']:
683 break
684 time.sleep(1)
685
686 if response['status'] == 'FAILURE':
687 return False
688 if response['status'] == 'COMPLETED':
689 return True
690
691 def _get_policy_id(self):
692 policy_id = None
693 uri = "https://{0}:{1}/mgmt/tm/asm/policies/".format(
694 self.client.provider['server'],
695 self.client.provider['server_port'],
696 )
697 query = "?$filter=contains(name,'{0}')+and+contains(partition,'{1}')&$select=name,id,partition".format(
698 self.want.name, self.want.partition
699 )
700 resp = self.client.api.get(uri + query)
701 try:
702 response = resp.json()
703 except ValueError as ex:
704 raise F5ModuleError(str(ex))
705
706 if resp.status not in [200, 201] or 'code' in response and response['code'] not in [200, 201]:
707 raise F5ModuleError(resp.content)
708
709 if 'items' in response and response['items'] != []:
710 # because api filter on ASM is broken when names that contain numbers at the end we need to work around it
711 for policy in response['items']:
712 if policy['name'] == self.want.name and policy['partition'] == self.want.partition:
713 policy_id = policy['id']
714
715 if not policy_id:
716 raise F5ModuleError(
717 "The policy with the name {0} was not found.".format(self.want.name)
718 )
719 return policy_id
720
721 def update_on_device(self):
722 params = self.changes.api_params()
723 # we need to remove active or apply from params as API will raise an error if the active or apply is set to yes,
724 # policies can only be activated or applied via apply-policy task endpoint.
725
726 params.pop('active', None)
727 params.pop('isModified', None)
728
729 if params:
730 policy_id = self._get_policy_id()
731 uri = "https://{0}:{1}/mgmt/tm/asm/policies/{2}".format(
732 self.client.provider['server'],
733 self.client.provider['server_port'],
734 policy_id
735 )
736 resp = self.client.api.patch(uri, json=params)
737
738 try:
739 response = resp.json()
740 except ValueError as ex:
741 raise F5ModuleError(str(ex))
742
743 if resp.status in [200, 201] or 'code' in response and response['code'] in [200, 201]:
744 return True
745 raise F5ModuleError(resp.content)
746
747 def read_current_from_device(self):
748 policy_id = self._get_policy_id()
749 uri = "https://{0}:{1}/mgmt/tm/asm/policies/{2}".format(
750 self.client.provider['server'],
751 self.client.provider['server_port'],
752 policy_id
753 )
754 resp = self.client.api.get(uri)
755
756 try:
757 response = resp.json()
758 except ValueError as ex:
759 raise F5ModuleError(str(ex))
760 if resp.status in [200, 201] or 'code' in response and response['code'] in [200, 201]:
761 response.update((dict(self_link=response['selfLink'])))
762 return Parameters(params=response)
763 raise F5ModuleError(resp.content)
764
765 def apply_on_device(self):
766 uri = "https://{0}:{1}/mgmt/tm/asm/tasks/apply-policy/".format(
767 self.client.provider['server'],
768 self.client.provider['server_port'],
769 )
770 params = dict(policyReference={'link': self.have.self_link})
771 resp = self.client.api.post(uri, json=params)
772
773 try:
774 response = resp.json()
775 except ValueError as ex:
776 raise F5ModuleError(str(ex))
777
778 if resp.status in [200, 201] or 'code' in response and response['code'] in [200, 201]:
779 return response['id']
780 raise F5ModuleError(resp.content)
781
782 def create_from_template_on_device(self):
783 full_name = fq_name(self.want.partition, self.want.name)
784 cmd = 'tmsh create asm policy {0} policy-template {1} encoding utf-8'.format(full_name, self.want.template)
785 uri = "https://{0}:{1}/mgmt/tm/util/bash/".format(
786 self.client.provider['server'],
787 self.client.provider['server_port'],
788 )
789 args = dict(
790 command='run',
791 utilCmdArgs='-c "{0}"'.format(cmd)
792 )
793 resp = self.client.api.post(uri, json=args)
794
795 try:
796 response = resp.json()
797 if 'commandResult' in response:
798 if 'Error' in response['commandResult'] or 'error' in response['commandResult']:
799 raise F5ModuleError(response['commandResult'])
800 except ValueError as ex:
801 raise F5ModuleError(str(ex))
802
803 if resp.status in [200, 201] or 'code' in response and response['code'] in [200, 201]:
804 return True
805 raise F5ModuleError(resp.content)
806
807 def create_on_device(self):
808 params = self.changes.api_params()
809 params['name'] = self.want.name
810 params['partition'] = self.want.partition
811 # we need to remove active or apply from params as API will raise an error if the active or apply is set to yes,
812 # policies can only be activated or applied via apply-policy task endpoint.
813 params.pop('active', None)
814 params.pop('isModified', None)
815 uri = "https://{0}:{1}/mgmt/tm/asm/policies/".format(
816 self.client.provider['server'],
817 self.client.provider['server_port'],
818 )
819 resp = self.client.api.post(uri, json=params)
820
821 try:
822 response = resp.json()
823 except ValueError as ex:
824 raise F5ModuleError(str(ex))
825
826 if resp.status in [200, 201] or 'code' in response and response['code'] in [200, 201]:
827 time.sleep(2)
828 return True
829 raise F5ModuleError(resp.content)
830
831 def remove_from_device(self):
832 policy_id = self._get_policy_id()
833 uri = "https://{0}:{1}/mgmt/tm/asm/policies/{2}".format(
834 self.client.provider['server'],
835 self.client.provider['server_port'],
836 policy_id
837 )
838 response = self.client.api.delete(uri)
839 if response.status in [200, 201]:
840 return True
841 raise F5ModuleError(response.content)
842
843
844 class ModuleManager(object):
845 def __init__(self, *args, **kwargs):
846 self.module = kwargs.get('module', None)
847 self.client = F5RestClient(**self.module.params)
848 self.kwargs = kwargs
849
850 def exec_module(self):
851 if not module_provisioned(self.client, 'asm'):
852 raise F5ModuleError(
853 "ASM must be provisioned to use this module."
854 )
855 if self.version_is_less_than_13():
856 manager = self.get_manager('v1')
857 else:
858 manager = self.get_manager('v2')
859 return manager.exec_module()
860
861 def get_manager(self, type):
862 if type == 'v1':
863 return V1Manager(**self.kwargs)
864 elif type == 'v2':
865 return V2Manager(**self.kwargs)
866
867 def version_is_less_than_13(self):
868 version = tmos_version(self.client)
869 if Version(version) < Version('13.0.0'):
870 return True
871 else:
872 return False
873
874
875 class V1Manager(BaseManager):
876 def __init__(self, *args, **kwargs):
877 module = kwargs.get('module', None)
878 client = F5RestClient(**module.params)
879 super(V1Manager, self).__init__(client=client, module=module)
880 self.want = V1ModuleParameters(params=module.params, client=client)
881
882 def create_from_template(self):
883 self.create_from_template_on_device()
884
885
886 class V2Manager(BaseManager):
887 def __init__(self, *args, **kwargs):
888 module = kwargs.get('module', None)
889 client = F5RestClient(**module.params)
890 super(V2Manager, self).__init__(client=client, module=module)
891 self.want = V2ModuleParameters(params=module.params, client=client)
892
893 # TODO Include creating ASM policies from custom templates in v13
894
895 def create_from_template(self):
896 if not self.create_from_template_on_device():
897 return False
898
899
900 class ArgumentSpec(object):
901 def __init__(self):
902 self.template_map = [
903 'ActiveSync v1.0 v2.0 (http)',
904 'ActiveSync v1.0 v2.0 (https)',
905 'Comprehensive',
906 'Drupal',
907 'Fundamental',
908 'Joomla',
909 'LotusDomino 6.5 (http)',
910 'LotusDomino 6.5 (https)',
911 'OWA Exchange 2003 (http)',
912 'OWA Exchange 2003 (https)',
913 'OWA Exchange 2003 with ActiveSync (http)',
914 'OWA Exchange 2003 with ActiveSync (https)',
915 'OWA Exchange 2007 (http)',
916 'OWA Exchange 2007 (https)',
917 'OWA Exchange 2007 with ActiveSync (http)',
918 'OWA Exchange 2007 with ActiveSync (https)',
919 'OWA Exchange 2010 (http)',
920 'OWA Exchange 2010 (https)',
921 'Oracle 10g Portal (http)',
922 'Oracle 10g Portal (https)',
923 'Oracle Applications 11i (http)',
924 'Oracle Applications 11i (https)',
925 'PeopleSoft Portal 9 (http)',
926 'PeopleSoft Portal 9 (https)',
927 'Rapid Deployment Policy',
928 'SAP NetWeaver 7 (http)',
929 'SAP NetWeaver 7 (https)',
930 'SharePoint 2003 (http)',
931 'SharePoint 2003 (https)',
932 'SharePoint 2007 (http)',
933 'SharePoint 2007 (https)',
934 'SharePoint 2010 (http)',
935 'SharePoint 2010 (https)',
936 'Vulnerability Assessment Baseline',
937 'Wordpress',
938 ]
939 self.supports_check_mode = True
940 argument_spec = dict(
941 name=dict(
942 required=True,
943 ),
944 template=dict(
945 choices=self.template_map
946 ),
947 active=dict(
948 type='bool'
949 ),
950 apply=dict(
951 type='bool',
952 ),
953 state=dict(
954 default='present',
955 choices=['present', 'absent']
956 ),
957 partition=dict(
958 default='Common',
959 fallback=(env_fallback, ['F5_PARTITION'])
960 )
961 )
962 self.argument_spec = {}
963 self.argument_spec.update(f5_argument_spec)
964 self.argument_spec.update(argument_spec)
965
966
967 def main():
968 spec = ArgumentSpec()
969
970 module = AnsibleModule(
971 argument_spec=spec.argument_spec,
972 supports_check_mode=spec.supports_check_mode,
973 )
974
975 if not HAS_PACKAGING:
976 module.fail_json(
977 msg=missing_required_lib('packaging'),
978 exception=PACKAGING_IMPORT_ERROR
979 )
980
981 try:
982 mm = ModuleManager(module=module)
983 results = mm.exec_module()
984 module.exit_json(**results)
985 except F5ModuleError as ex:
986 module.fail_json(msg=str(ex))
987
988
989 if __name__ == '__main__':
990 main()