Debian Codegraph @

ansible_collections/f5networks/f5_modules/plugins/modules/bigip_irule.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 __metaclass__ = type
9
10 DOCUMENTATION = r'''
11 ---
12 module: bigip_irule
13 short_description: Manage iRules across different modules on a BIG-IP
14 description:
15 - Manage iRules across different modules on a BIG-IP device.
16 version_added: "1.0.0"
17 options:
18 content:
19 description:
20 - When used instead of B(src), sets the contents of an iRule directly to
21 the specified value. This is for simple values, but can be used with
22 lookup plugins for anything complex or with formatting. Either one
23 of C(src) or C(content) must be provided.
24 type: str
25 module:
26 description:
27 - The BIG-IP module to which the iRule should be added.
28 type: str
29 required: True
30 choices:
31 - ltm
32 - gtm
33 name:
34 description:
35 - The name of the iRule.
36 type: str
37 required: True
38 src:
39 description:
40 - The iRule file to interpret and upload to the BIG-IP. Either one
41 of C(src) or C(content) must be provided.
42 type: path
43 state:
44 description:
45 - Whether the iRule should exist or not.
46 type: str
47 choices:
48 - present
49 - absent
50 default: present
51 partition:
52 description:
53 - Device partition to manage resources on.
54 type: str
55 default: Common
56 extends_documentation_fragment: f5networks.f5_modules.f5
57 author:
58 - Tim Rupp (@caphrim007)
59 - Wojciech Wypior (@wojtek0806)
60 '''
61
62 EXAMPLES = r'''
63 - name: Add the iRule contained in template irule.tcl to the LTM module
64 bigip_irule:
65 content: "{{ lookup('template', 'irule.tcl') }}"
66 module: ltm
67 name: MyiRule
68 state: present
69 provider:
70 user: admin
71 password: secret
72 server: lb.mydomain.com
73 delegate_to: localhost
74
75 - name: Add the iRule contained in static file irule.tcl to the LTM module
76 bigip_irule:
77 module: ltm
78 name: MyiRule
79 src: irule.tcl
80 state: present
81 provider:
82 user: admin
83 password: secret
84 server: lb.mydomain.com
85 delegate_to: localhost
86 '''
87
88 RETURN = r'''
89 module:
90 description: The module that the iRule was added to.
91 returned: changed and success
92 type: str
93 sample: gtm
94 src:
95 description: The filename that included the iRule source.
96 returned: changed and success, when provided
97 type: str
98 sample: /opt/src/irules/example1.tcl
99 content:
100 description: The content of the iRule that was managed.
101 returned: changed and success
102 type: str
103 sample: "when LB_FAILED { set wipHost [LB::server addr] }"
104 '''
105
106 import os
107 from datetime import datetime
108
109 from ansible.module_utils.basic import (
110 AnsibleModule, env_fallback
111 )
112
113 from ..module_utils.bigip import F5RestClient
114 from ..module_utils.common import (
115 F5ModuleError, AnsibleF5Parameters, transform_name, f5_argument_spec
116 )
117 from ..module_utils.icontrol import tmos_version
118 from ..module_utils.teem import send_teem
119
120
121 class Parameters(AnsibleF5Parameters):
122 api_map = {
123 'apiAnonymous': 'content',
124 }
125
126 updatables = [
127 'content',
128 ]
129
130 api_attributes = [
131 'apiAnonymous',
132 ]
133
134 returnables = [
135 'content', 'src', 'module',
136 ]
137
138
139 class ApiParameters(Parameters):
140 pass
141
142
143 class ModuleParameters(Parameters):
144 @property
145 def content(self):
146 if self._values['content'] is None:
147 result = self.src_content
148 else:
149 result = self._values['content']
150
151 return str(result).strip()
152
153 @property
154 def src(self):
155 if self._values['src'] is None:
156 return None
157 return self._values['src']
158
159 @property
160 def src_content(self):
161 if not os.path.exists(self._values['src']):
162 raise F5ModuleError(
163 "The specified 'src' was not found."
164 )
165 with open(self._values['src']) as f:
166 result = f.read()
167 return result
168
169
170 class Changes(Parameters):
171 def to_return(self):
172 result = {}
173 try:
174 for returnable in self.returnables:
175 result[returnable] = getattr(self, returnable)
176 result = self._filter_params(result)
177 except Exception:
178 raise
179 return result
180
181
182 class UsableChanges(Changes):
183 pass
184
185
186 class ReportableChanges(Changes):
187 pass
188
189
190 class Difference(object):
191 def __init__(self, want, have=None):
192 self.want = want
193 self.have = have
194
195 def compare(self, param):
196 try:
197 result = getattr(self, param)
198 return result
199 except AttributeError:
200 return self.__default(param)
201
202 def __default(self, param):
203 attr1 = getattr(self.want, param)
204 try:
205 attr2 = getattr(self.have, param)
206 if attr1 != attr2:
207 return attr1
208 except AttributeError:
209 return attr1
210
211
212 class ModuleManager(object):
213 def __init__(self, *args, **kwargs):
214 self.client = kwargs.get('client', None)
215 self.module = kwargs.get('module', None)
216 self.kwargs = kwargs
217
218 def exec_module(self):
219 if self.module.params['module'] == 'ltm':
220 manager = self.get_manager('ltm')
221 elif self.module.params['module'] == 'gtm':
222 manager = self.get_manager('gtm')
223 else:
224 raise F5ModuleError(
225 "An unknown iRule module type was specified"
226 )
227 return manager.exec_module()
228
229 def get_manager(self, type):
230 if type == 'ltm':
231 return LtmManager(**self.kwargs)
232 elif type == 'gtm':
233 return GtmManager(**self.kwargs)
234
235
236 class BaseManager(object):
237 def __init__(self, *args, **kwargs):
238 self.module = kwargs.get('module', None)
239 self.client = F5RestClient(**self.module.params)
240 self.have = None
241 self.want = ModuleParameters(params=self.module.params)
242 self.changes = UsableChanges()
243
244 def _set_changed_options(self):
245 changed = {}
246 for key in Parameters.returnables:
247 if getattr(self.want, key) is not None:
248 changed[key] = getattr(self.want, key)
249 if changed:
250 self.changes = UsableChanges(params=changed)
251
252 def _update_changed_options(self):
253 diff = Difference(self.want, self.have)
254 updatables = Parameters.updatables
255 changed = dict()
256 for k in updatables:
257 change = diff.compare(k)
258 if change is None:
259 continue
260 else:
261 if isinstance(change, dict):
262 changed.update(change)
263 else:
264 changed[k] = change
265 if changed:
266 self.changes = UsableChanges(params=changed)
267 return True
268 return False
269
270 def _announce_deprecations(self, result):
271 warnings = result.pop('__warnings', [])
272 for warning in warnings:
273 self.module.deprecate(
274 msg=warning['msg'],
275 version=warning['version']
276 )
277
278 def exec_module(self):
279 start = datetime.now().isoformat()
280 version = tmos_version(self.client)
281 changed = False
282 result = dict()
283 state = self.want.state
284
285 if state in ["present"]:
286 changed = self.present()
287 elif state == "absent":
288 changed = self.absent()
289
290 reportable = ReportableChanges(params=self.changes.to_return())
291 changes = reportable.to_return()
292 result.update(**changes)
293 result.update(dict(changed=changed))
294 self._announce_deprecations(result)
295 send_teem(start, self.client, self.module, version)
296 return result
297
298 def present(self):
299 if not self.want.content and not self.want.src:
300 raise F5ModuleError(
301 "Either 'content' or 'src' must be provided"
302 )
303 if self.exists():
304 return self.update()
305 else:
306 return self.create()
307
308 def create(self):
309 self._set_changed_options()
310 if self.module.check_mode:
311 return True
312 self.create_on_device()
313 if not self.exists():
314 raise F5ModuleError("Failed to create the iRule")
315 return True
316
317 def should_update(self):
318 result = self._update_changed_options()
319 if result:
320 return True
321 return False
322
323 def update(self):
324 self.have = self.read_current_from_device()
325 if not self.should_update():
326 return False
327 if self.module.check_mode:
328 return True
329 self.update_on_device()
330 return True
331
332 def absent(self):
333 if self.exists():
334 return self.remove()
335 return False
336
337 def remove(self):
338 if self.module.check_mode:
339 return True
340 self.remove_from_device()
341 if self.exists():
342 raise F5ModuleError("Failed to delete the iRule")
343 return True
344
345
346 class LtmManager(BaseManager):
347 def exists(self):
348 uri = "https://{0}:{1}/mgmt/tm/ltm/rule/{2}".format(
349 self.client.provider['server'],
350 self.client.provider['server_port'],
351 transform_name(self.want.partition, self.want.name)
352 )
353 resp = self.client.api.get(uri)
354 try:
355 response = resp.json()
356 except ValueError as ex:
357 raise F5ModuleError(str(ex))
358
359 if resp.status == 404 or 'code' in response and response['code'] == 404:
360 return False
361 if resp.status in [200, 201] or 'code' in response and response['code'] in [200, 201]:
362 return True
363
364 errors = [401, 403, 409, 500, 501, 502, 503, 504]
365
366 if resp.status in errors or 'code' in response and response['code'] in errors:
367 if 'message' in response:
368 raise F5ModuleError(response['message'])
369 else:
370 raise F5ModuleError(resp.content)
371
372 def update_on_device(self):
373 params = self.changes.api_params()
374 uri = "https://{0}:{1}/mgmt/tm/ltm/rule/{2}".format(
375 self.client.provider['server'],
376 self.client.provider['server_port'],
377 transform_name(self.want.partition, self.want.name)
378 )
379 resp = self.client.api.patch(uri, json=params)
380 try:
381 response = resp.json()
382 except ValueError as ex:
383 raise F5ModuleError(str(ex))
384
385 if resp.status in [200, 201] or 'code' in response and response['code'] in [200, 201]:
386 return True
387 raise F5ModuleError(resp.content)
388
389 def create_on_device(self):
390 params = self.changes.api_params()
391 params['name'] = self.want.name
392 params['partition'] = self.want.partition
393 uri = "https://{0}:{1}/mgmt/tm/ltm/rule/".format(
394 self.client.provider['server'],
395 self.client.provider['server_port'],
396 )
397 resp = self.client.api.post(uri, json=params)
398 try:
399 response = resp.json()
400 except ValueError as ex:
401 raise F5ModuleError(str(ex))
402
403 if resp.status in [200, 201] or 'code' in response and response['code'] in [200, 201]:
404 return True
405 raise F5ModuleError(resp.content)
406
407 def read_current_from_device(self):
408 uri = "https://{0}:{1}/mgmt/tm/ltm/rule/{2}".format(
409 self.client.provider['server'],
410 self.client.provider['server_port'],
411 transform_name(self.want.partition, self.want.name)
412 )
413
414 resp = self.client.api.get(uri)
415
416 try:
417 response = resp.json()
418 except ValueError as ex:
419 raise F5ModuleError(str(ex))
420
421 if resp.status in [200, 201] or 'code' in response and response['code'] in [200, 201]:
422 return ApiParameters(params=response)
423 raise F5ModuleError(resp.content)
424
425 def remove_from_device(self):
426 uri = "https://{0}:{1}/mgmt/tm/ltm/rule/{2}".format(
427 self.client.provider['server'],
428 self.client.provider['server_port'],
429 transform_name(self.want.partition, self.want.name)
430 )
431 response = self.client.api.delete(uri)
432
433 if response.status in [200, 201]:
434 return True
435 raise F5ModuleError(response.content)
436
437
438 class GtmManager(BaseManager):
439 def exists(self):
440 uri = "https://{0}:{1}/mgmt/tm/gtm/rule/{2}".format(
441 self.client.provider['server'],
442 self.client.provider['server_port'],
443 transform_name(self.want.partition, self.want.name)
444 )
445 resp = self.client.api.get(uri)
446 try:
447 response = resp.json()
448 except ValueError:
449 return False
450 if resp.status == 404 or 'code' in response and response['code'] == 404:
451 return False
452 return True
453
454 def update_on_device(self):
455 params = self.changes.api_params()
456 uri = "https://{0}:{1}/mgmt/tm/gtm/rule/{2}".format(
457 self.client.provider['server'],
458 self.client.provider['server_port'],
459 transform_name(self.want.partition, self.want.name)
460 )
461 resp = self.client.api.patch(uri, json=params)
462 try:
463 response = resp.json()
464 except ValueError as ex:
465 raise F5ModuleError(str(ex))
466
467 if resp.status in [200, 201] or 'code' in response and response['code'] in [200, 201]:
468 return True
469 raise F5ModuleError(resp.content)
470
471 def create_on_device(self):
472 params = self.changes.api_params()
473 params['name'] = self.want.name
474 params['partition'] = self.want.partition
475 uri = "https://{0}:{1}/mgmt/tm/gtm/rule/".format(
476 self.client.provider['server'],
477 self.client.provider['server_port'],
478 )
479 resp = self.client.api.post(uri, json=params)
480 try:
481 response = resp.json()
482 except ValueError as ex:
483 raise F5ModuleError(str(ex))
484
485 if resp.status in [200, 201] or 'code' in response and response['code'] in [200, 201]:
486 return True
487 raise F5ModuleError(resp.content)
488
489 def read_current_from_device(self):
490 uri = "https://{0}:{1}/mgmt/tm/gtm/rule/{2}".format(
491 self.client.provider['server'],
492 self.client.provider['server_port'],
493 transform_name(self.want.partition, self.want.name)
494 )
495
496 resp = self.client.api.get(uri)
497
498 try:
499 response = resp.json()
500 except ValueError as ex:
501 raise F5ModuleError(str(ex))
502
503 if resp.status in [200, 201] or 'code' in response and response['code'] in [200, 201]:
504 return ApiParameters(params=response)
505 raise F5ModuleError(resp.content)
506
507 def remove_from_device(self):
508 uri = "https://{0}:{1}/mgmt/tm/gtm/rule/{2}".format(
509 self.client.provider['server'],
510 self.client.provider['server_port'],
511 transform_name(self.want.partition, self.want.name)
512 )
513 response = self.client.api.delete(uri)
514
515 if response.status in [200, 201]:
516 return True
517 raise F5ModuleError(response.content)
518
519
520 class ArgumentSpec(object):
521 def __init__(self):
522 self.supports_check_mode = True
523 argument_spec = dict(
524 content=dict(),
525 src=dict(
526 type='path',
527 ),
528 name=dict(required=True),
529 module=dict(
530 required=True,
531 choices=['gtm', 'ltm']
532 ),
533 state=dict(
534 default='present',
535 choices=['present', 'absent']
536 ),
537 partition=dict(
538 default='Common',
539 fallback=(env_fallback, ['F5_PARTITION'])
540 )
541 )
542 self.argument_spec = {}
543 self.argument_spec.update(f5_argument_spec)
544 self.argument_spec.update(argument_spec)
545 self.mutually_exclusive = [
546 ['content', 'src']
547 ]
548
549
550 def main():
551 spec = ArgumentSpec()
552
553 module = AnsibleModule(
554 argument_spec=spec.argument_spec,
555 supports_check_mode=spec.supports_check_mode,
556 mutually_exclusive=spec.mutually_exclusive
557 )
558
559 try:
560 mm = ModuleManager(module=module)
561 results = mm.exec_module()
562 module.exit_json(**results)
563 except F5ModuleError as ex:
564 module.fail_json(msg=str(ex))
565
566
567 if __name__ == '__main__':
568 main()