Debian Codegraph @

ansible_collections/f5networks/f5_modules/plugins/modules/bigip_asm_policy_fetch.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_fetch
13 short_description: Exports the ASM policy from remote nodes.
14 description:
15 - Exports the ASM policy from remote nodes.
16 version_added: "1.0.0"
17 options:
18 name:
19 description:
20 - The name of the policy exported to create a file on the remote device for downloading.
21 type: str
22 required: True
23 dest:
24 description:
25 - A directory to save the policy file into.
26 - This option is ignored when C(inline) is set to C(true).
27 type: path
28 file:
29 description:
30 - The name of the file to be created on the remote device for downloading.
31 - When C(binary) is set to C(false) the ASM policy is in XML format.
32 type: str
33 inline:
34 description:
35 - If C(true), the ASM policy is exported C(inline) as a string instead of a file.
36 - The policy can be be retrieved in the playbook C(result) dictionary under the C(inline_policy) key.
37 type: bool
38 compact:
39 description:
40 - If C(true), only the ASM policy custom settings is exported.
41 - Only applies to XML type ASM policy exports.
42 type: bool
43 base64:
44 description:
45 - If C(true), the returned C(inline) ASM policy content is Base64 encoded.
46 - Only applies to C(inline) ASM policy exports.
47 type: bool
48 binary:
49 description:
50 - If C(true), the exported ASM policy is in binary format.
51 - Only applies to C(file) ASM policy exports.
52 type: bool
53 force:
54 description:
55 - If C(false), the file will only be transferred if it does not exist in the the destination.
56 default: true
57 type: bool
58 partition:
59 description:
60 - Device partition which contains the ASM policy to export.
61 type: str
62 default: Common
63 extends_documentation_fragment: f5networks.f5_modules.f5
64 author:
65 - Wojciech Wypior (@wojtek0806)
66 - Nitin Khanna (@nitinthewiz)
67 '''
68
69 EXAMPLES = r'''
70 - name: Export policy in binary format
71 bigip_asm_policy_fetch:
72 name: foobar
73 file: export_foo
74 dest: /root/download
75 binary: true
76 provider:
77 password: secret
78 server: lb.mydomain.com
79 user: admin
80 delegate_to: localhost
81
82 - name: Export policy inline base64 encoded format
83 bigip_asm_policy_fetch:
84 name: foobar
85 inline: true
86 base64: true
87 provider:
88 password: secret
89 server: lb.mydomain.com
90 user: admin
91 delegate_to: localhost
92
93 - name: Export policy in XML format
94 bigip_asm_policy_fetch:
95 name: foobar
96 file: export_foo
97 dest: /root/download
98 provider:
99 password: secret
100 server: lb.mydomain.com
101 user: admin
102 delegate_to: localhost
103
104 - name: Export compact policy in XML format
105 bigip_asm_policy_fetch:
106 name: foobar
107 file: export_foo.xml
108 dest: /root/download/
109 compact: true
110 provider:
111 password: secret
112 server: lb.mydomain.com
113 user: admin
114 delegate_to: localhost
115
116 - name: Export policy in binary format, autogenerate name
117 bigip_asm_policy_fetch:
118 name: foobar
119 dest: /root/download/
120 binary: true
121 provider:
122 password: secret
123 server: lb.mydomain.com
124 user: admin
125 delegate_to: localhost
126 '''
127
128 RETURN = r'''
129 name:
130 description: Name of the ASM policy to be exported.
131 returned: changed
132 type: str
133 sample: Asm_APP1_Transparent
134 dest:
135 description: Local path to download the exported ASM policy.
136 returned: changed
137 type: str
138 sample: /root/downloads/foobar.xml
139 file:
140 description:
141 - Name of the policy file on the remote BIG-IP to download. If not
142 specified, then this is a randomly generated filename.
143 returned: changed
144 type: str
145 sample: foobar.xml
146 inline:
147 description: Set when the ASM policy to be exported is inline
148 returned: changed
149 type: bool
150 sample: true
151 compact:
152 description: Set only to export custom ASM policy settings.
153 returned: changed
154 type: bool
155 sample: false
156 base64:
157 description: Set to encode inline export in Base64 format.
158 returned: changed
159 type: bool
160 sample: false
161 binary:
162 description: Set to export the ASM policy in binary format.
163 returned: changed
164 type: bool
165 sample: true
166 '''
167
168 import os
169 import time
170 import tempfile
171 from datetime import datetime
172
173 from ansible.module_utils.basic import (
174 AnsibleModule, env_fallback
175 )
176 from ..module_utils.bigip import F5RestClient
177 from ..module_utils.common import (
178 F5ModuleError, AnsibleF5Parameters, f5_argument_spec, flatten_boolean, fq_name
179 )
180 from ..module_utils.icontrol import (
181 module_provisioned, download_asm_file, tmos_version
182 )
183 from ..module_utils.teem import send_teem
184
185
186 class Parameters(AnsibleF5Parameters):
187 api_map = {
188 'filename': 'file',
189 'minimal': 'compact',
190 'isBase64': 'base64',
191 }
192
193 api_attributes = [
194 'inline',
195 'minimal',
196 'isBase64',
197 'policyReference',
198 'filename',
199 ]
200
201 returnables = [
202 'file',
203 'compact',
204 'base64',
205 'inline',
206 'force',
207 'binary',
208 'dest',
209 'name',
210 'inline_policy',
211 ]
212
213 updatables = [
214
215 ]
216
217
218 class ApiParameters(Parameters):
219 pass
220
221
222 class ModuleParameters(Parameters):
223 @property
224 def file(self):
225 if self._values['file'] is not None:
226 return self._values['file']
227 if self.binary:
228 result = next(tempfile._get_candidate_names()) + '.plc'
229 else:
230 result = next(tempfile._get_candidate_names()) + '.xml'
231 self._values['file'] = result
232 return result
233
234 @property
235 def fulldest(self):
236 if os.path.isdir(self.dest):
237 result = os.path.join(self.dest, self.file)
238 else:
239 if os.path.exists(os.path.dirname(self.dest)):
240 result = self.dest
241 else:
242 try:
243 # os.path.exists() can return false in some
244 # circumstances where the directory does not have
245 # the execute bit for the current user set, in
246 # which case the stat() call will raise an OSError
247 result = self.dest
248 os.stat(os.path.dirname(result))
249 except OSError as e:
250 if "permission denied" in str(e).lower():
251 raise F5ModuleError(
252 "Destination directory {0} is not accessible".format(os.path.dirname(self.dest))
253 )
254 raise F5ModuleError(
255 "Destination directory {0} does not exist".format(os.path.dirname(self.dest))
256 )
257
258 if not os.access(os.path.dirname(result), os.W_OK):
259 raise F5ModuleError(
260 "Destination {0} not writable".format(os.path.dirname(result))
261 )
262 return result
263
264 @property
265 def inline(self):
266 result = flatten_boolean(self._values['inline'])
267 if result == 'yes':
268 return True
269 elif result == 'no':
270 return False
271
272 @property
273 def compact(self):
274 result = flatten_boolean(self._values['compact'])
275 if result == 'yes':
276 return True
277 elif result == 'no':
278 return False
279
280 @property
281 def base64(self):
282 result = flatten_boolean(self._values['base64'])
283 if result == 'yes':
284 return True
285 elif result == 'no':
286 return False
287
288
289 class Changes(Parameters):
290 def to_return(self):
291 result = {}
292 try:
293 for returnable in self.returnables:
294 result[returnable] = getattr(self, returnable)
295 result = self._filter_params(result)
296 except Exception:
297 raise
298 return result
299
300
301 class UsableChanges(Changes):
302 pass
303
304
305 class ReportableChanges(Changes):
306 pass
307
308
309 class ModuleManager(object):
310 def __init__(self, *args, **kwargs):
311 self.module = kwargs.get('module', None)
312 self.client = F5RestClient(**self.module.params)
313 self.want = ModuleParameters(params=self.module.params)
314 self.changes = UsableChanges()
315
316 def _set_changed_options(self):
317 changed = {}
318 for key in Parameters.returnables:
319 if getattr(self.want, key) is not None:
320 changed[key] = getattr(self.want, key)
321 if changed:
322 self.changes = UsableChanges(params=changed)
323
324 def _announce_deprecations(self, result):
325 warnings = result.pop('__warnings', [])
326 for warning in warnings:
327 self.client.module.deprecate(
328 msg=warning['msg'],
329 version=warning['version']
330 )
331
332 def exec_module(self):
333 start = datetime.now().isoformat()
334 version = tmos_version(self.client)
335 if not module_provisioned(self.client, 'asm'):
336 raise F5ModuleError(
337 "ASM must be provisioned to use this module."
338 )
339 result = dict()
340
341 self.export()
342
343 reportable = ReportableChanges(params=self.changes.to_return())
344 changes = reportable.to_return()
345 result.update(**changes)
346 result.update(dict(changed=True))
347 send_teem(start, self.client, self.module, version)
348 return result
349
350 def export(self):
351 if self.exists():
352 return self.update()
353 else:
354 return self.create()
355
356 def update(self):
357 if not self.want.force:
358 raise F5ModuleError(
359 "File '{0}' already exists.".format(self.want.fulldest)
360 )
361 self.create()
362
363 def create(self):
364 self._set_changed_options()
365 if self.module.check_mode:
366 return True
367 if self.want.binary:
368 self.export_binary()
369 return True
370 self.create_on_device()
371 if not self.want.inline:
372 self.execute()
373 return True
374
375 def export_binary(self):
376 self.export_binary_on_device()
377 self.execute()
378 return True
379
380 def download(self):
381 self.download_from_device(self.want.fulldest)
382 if os.path.exists(self.want.fulldest):
383 return True
384 raise F5ModuleError(
385 "Failed to download the remote file."
386 )
387
388 def execute(self):
389 self.download()
390 self.remove_temp_policy_from_device()
391 return True
392
393 def exists(self):
394 self.policy_exists()
395 if not self.want.inline:
396 if os.path.exists(self.want.fulldest):
397 return True
398 return False
399
400 def policy_exists(self):
401 uri = 'https://{0}:{1}/mgmt/tm/asm/policies/'.format(
402 self.client.provider['server'],
403 self.client.provider['server_port'],
404 )
405 query = "?$filter=contains(name,'{0}')+and+contains(partition,'{1}')&$select=name,partition".format(
406 self.want.name, self.want.partition
407 )
408 resp = self.client.api.get(uri + query)
409 try:
410 response = resp.json()
411 except ValueError as ex:
412 raise F5ModuleError(str(ex))
413
414 if resp.status not in [200, 201] or 'code' in response and response['code'] not in [200, 201]:
415 raise F5ModuleError(resp.content)
416
417 if 'items' in response and response['items'] != []:
418 # because api filter on ASM is broken when names that contain numbers at the end we need to work around it
419 for policy in response['items']:
420 if policy['name'] == self.want.name and policy['partition'] == self.want.partition:
421 return True
422 raise F5ModuleError(
423 "The specified ASM policy {0} on partition {1} does not exist on device.".format(
424 self.want.name, self.want.partition
425 )
426 )
427
428 def create_on_device(self):
429 self._set_policy_link()
430 params = self.changes.api_params()
431 uri = "https://{0}:{1}/mgmt/tm/asm/tasks/export-policy/".format(
432 self.client.provider['server'],
433 self.client.provider['server_port'],
434 )
435 resp = self.client.api.post(uri, json=params)
436
437 try:
438 response = resp.json()
439 except ValueError as ex:
440 raise F5ModuleError(str(ex))
441
442 if resp.status not in [200, 201] or 'code' in response and response['code'] not in [200, 201]:
443 raise F5ModuleError(resp.content)
444
445 result, output, file_size = self.wait_for_task(response['id'])
446 if result and output:
447 if 'file' in output:
448 self.changes.update(dict(inline_policy=output['file']))
449 if result:
450 self.want.file_size = file_size
451 return True
452
453 def wait_for_task(self, task_id):
454 uri = "https://{0}:{1}/mgmt/tm/asm/tasks/export-policy/{2}".format(
455 self.client.provider['server'],
456 self.client.provider['server_port'],
457 task_id
458 )
459 while True:
460 resp = self.client.api.get(uri)
461
462 try:
463 response = resp.json()
464 except ValueError as ex:
465 raise F5ModuleError(str(ex))
466
467 if resp.status not in [200, 201] or 'code' in response and response['code'] not in [200, 201]:
468 raise F5ModuleError(resp.content)
469
470 if response['status'] in ['COMPLETED', 'FAILURE']:
471 break
472 time.sleep(1)
473
474 if response['status'] == 'FAILURE':
475 raise F5ModuleError(
476 'Failed to export ASM policy.'
477 )
478 if response['status'] == 'COMPLETED':
479 if not self.want.inline:
480 return True, None, response['result']['fileSize']
481 else:
482 return True, response['result'], response['result']['fileSize']
483
484 def _set_policy_link(self):
485 policy_link = None
486 uri = 'https://{0}:{1}/mgmt/tm/asm/policies/'.format(
487 self.client.provider['server'],
488 self.client.provider['server_port'],
489 )
490 query = "?$filter=contains(name,'{0}')+and+contains(partition,'{1}')&$select=name,partition".format(
491 self.want.name, self.want.partition
492 )
493 resp = self.client.api.get(uri + query)
494 try:
495 response = resp.json()
496 except ValueError as ex:
497 raise F5ModuleError(str(ex))
498 if 'items' in response and response['items'] != []:
499 # because api filter on ASM is broken when names that contain numbers at the end we need to work around it
500 for policy in response['items']:
501 if policy['name'] == self.want.name and policy['partition'] == self.want.partition:
502 policy_link = policy['selfLink']
503
504 if not policy_link:
505 raise F5ModuleError("The policy was not found")
506
507 self.changes.update(dict(policyReference={'link': policy_link}))
508 return True
509
510 def export_binary_on_device(self):
511 full_name = fq_name(self.want.partition, self.want.name)
512 cmd = 'tmsh save asm policy {0} bin-file {1}'.format(full_name, self.want.file)
513 uri = "https://{0}:{1}/mgmt/tm/util/bash/".format(
514 self.client.provider['server'],
515 self.client.provider['server_port'],
516 )
517 args = dict(
518 command='run',
519 utilCmdArgs='-c "{0}"'.format(cmd)
520 )
521 resp = self.client.api.post(uri, json=args)
522
523 try:
524 response = resp.json()
525 if 'commandResult' in response:
526 if 'Error' in response['commandResult'] or 'error' in response['commandResult']:
527 raise F5ModuleError(response['commandResult'])
528 except ValueError as ex:
529 raise F5ModuleError(str(ex))
530
531 if resp.status not in [200, 201] or 'code' in response and response['code'] not in [200, 201]:
532 raise F5ModuleError(resp.content)
533
534 self._stat_binary_on_device()
535 self._move_binary_to_download()
536
537 return True
538
539 def _stat_binary_on_device(self):
540 params = dict(
541 command='run',
542 utilCmdArgs='/var/tmp/{0} -l'.format(self.want.file)
543 )
544
545 uri = "https://{0}:{1}/mgmt/tm/util/unix-ls/".format(
546 self.client.provider['server'],
547 self.client.provider['server_port'],
548 )
549 resp = self.client.api.post(uri, json=params)
550
551 try:
552 response = resp.json()
553 except ValueError as ex:
554 raise F5ModuleError(str(ex))
555
556 if resp.status not in [200, 201] or 'code' in response and response['code'] not in [200, 201]:
557 raise F5ModuleError(resp.content)
558
559 if 'commandResult' not in response:
560 raise F5ModuleError("Failed to obtain file information, aborting.")
561
562 if 'Error' in response['commandResult'] or 'error' in response['commandResult']:
563 raise F5ModuleError(response['commandResult'])
564
565 if '/var/tmp/{0}'.format(self.want.file) not in response['commandResult']:
566 raise F5ModuleError("Cannot get size of exported binary file, aborting")
567
568 size = response['commandResult']
569
570 self.want.file_size = int(size.split()[4])
571 return True
572
573 def _move_binary_to_download(self):
574 name = '{0}~{1}'.format(self.client.provider['user'], self.want.file)
575 move_path = '/var/tmp/{0} {1}/{2}'.format(
576 self.want.file,
577 '/ts/var/rest',
578 name
579 )
580 params = dict(
581 command='run',
582 utilCmdArgs=move_path
583 )
584
585 uri = "https://{0}:{1}/mgmt/tm/util/unix-mv/".format(
586 self.client.provider['server'],
587 self.client.provider['server_port']
588 )
589
590 resp = self.client.api.post(uri, json=params)
591
592 try:
593 response = resp.json()
594 if 'commandResult' in response:
595 if 'cannot stat' in response['commandResult']:
596 raise F5ModuleError(response['commandResult'])
597 except ValueError as ex:
598 raise F5ModuleError(str(ex))
599
600 if resp.status in [200, 201] or 'code' in response and response['code'] in [200, 201]:
601 return True
602 raise F5ModuleError(resp.content)
603
604 def download_from_device(self, dest):
605 url = 'https://{0}:{1}/mgmt/tm/asm/file-transfer/downloads/{2}'.format(
606 self.client.provider['server'],
607 self.client.provider['server_port'],
608 self.want.file
609 )
610 try:
611 download_asm_file(self.client, url, dest, self.want.file_size)
612 except F5ModuleError:
613 raise F5ModuleError(
614 "Failed to download the file."
615 )
616 if os.path.exists(self.want.dest):
617 return True
618 return False
619
620 def remove_temp_policy_from_device(self):
621 name = '{0}~{1}'.format(self.client.provider['user'], self.want.file)
622 tpath_name = '/ts/var/rest/{0}'.format(name)
623 uri = "https://{0}:{1}/mgmt/tm/util/unix-rm/".format(
624 self.client.provider['server'],
625 self.client.provider['server_port'],
626 )
627 args = dict(
628 command='run',
629 utilCmdArgs=tpath_name
630 )
631 resp = self.client.api.post(uri, json=args)
632 try:
633 response = resp.json()
634 except ValueError as ex:
635 raise F5ModuleError(str(ex))
636
637 if resp.status in [200, 201] or 'code' in response and response['code'] in [200, 201]:
638 return True
639 raise F5ModuleError(resp.content)
640
641
642 class ArgumentSpec(object):
643 def __init__(self):
644 self.supports_check_mode = True
645 argument_spec = dict(
646 name=dict(
647 required=True,
648 ),
649 dest=dict(
650 type='path'
651 ),
652 file=dict(),
653 inline=dict(
654 type='bool'
655 ),
656 compact=dict(
657 type='bool'
658 ),
659 base64=dict(
660 type='bool'
661 ),
662 binary=dict(
663 type='bool'
664 ),
665 force=dict(
666 default='yes',
667 type='bool'
668 ),
669 partition=dict(
670 default='Common',
671 fallback=(env_fallback, ['F5_PARTITION'])
672 )
673 )
674 self.argument_spec = {}
675 self.argument_spec.update(f5_argument_spec)
676 self.argument_spec.update(argument_spec)
677 self.mutually_exclusive = [
678 ['binary', 'inline'],
679 ['binary', 'compact'],
680 ['dest', 'inline'],
681 ['file', 'inline']
682 ]
683
684
685 def main():
686 spec = ArgumentSpec()
687
688 module = AnsibleModule(
689 argument_spec=spec.argument_spec,
690 supports_check_mode=spec.supports_check_mode,
691 mutually_exclusive=spec.mutually_exclusive,
692 )
693
694 try:
695 mm = ModuleManager(module=module)
696 results = mm.exec_module()
697 module.exit_json(**results)
698 except F5ModuleError as ex:
699 module.fail_json(msg=str(ex))
700
701
702 if __name__ == '__main__':
703 main()