Debian Codegraph @

ansible_collections/f5networks/f5_modules/plugins/modules/bigip_file_copy.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_file_copy
13 short_description: Manage files in datastores on a BIG-IP
14 description:
15 - Manages files on a variety of datastores on a BIG-IP.
16 version_added: "1.0.0"
17 options:
18 name:
19 description:
20 - The name of the file as it should reside on the BIG-IP.
21 - If this is not specified, then the filename provided in the C(source)
22 parameter is used instead.
23 type: str
24 source:
25 description:
26 - Specifies the path of the file to upload.
27 - This parameter is required if C(state) is C(present).
28 type: path
29 aliases:
30 - src
31 datastore:
32 description:
33 - Specifies the datastore to put the file in.
34 - There are several different datastores and each of them allows files
35 to be exposed in different ways.
36 - When C(external-monitor), the specified file will be stored as
37 an external monitor file and be available for use in external monitors.
38 - When C(ifile), the specified file will be stored as an iFile.
39 - When C(lw4o6-table), the specified file will be stored as a Lightweight 4
40 over 6 (lw4o6) tunnel binding table, which includes an IPv6 address for the
41 lwB4, public IPv4 address, and restricted port set.
42 type: str
43 choices:
44 - external-monitor
45 - ifile
46 - lw4o6-table
47 default: ifile
48 force:
49 description:
50 - Force overwriting a file.
51 - By default, files are only overwritten if the SHA of the file is different
52 for the given filename. This parameter can be used to force overwriting the file
53 even if it already exists and its SHA matches.
54 - The C(lw4o6-table) datastore does not keep checksums of its file. Therefore, you
55 would need to provide this argument to update any of these files.
56 type: bool
57 default: false
58 partition:
59 description:
60 - Device partition to manage resources on.
61 type: str
62 default: Common
63 state:
64 description:
65 - When C(present), ensures the resource exists.
66 - When C(absent), ensures the resource is removed.
67 type: str
68 choices:
69 - present
70 - absent
71 default: present
72 extends_documentation_fragment: f5networks.f5_modules.f5
73 author:
74 - Tim Rupp (@caphrim007)
75 '''
76
77 EXAMPLES = r'''
78 - name: Upload a file as an iFile
79 bigip_file_copy:
80 name: foo
81 source: /path/to/file.txt
82 datastore: ifile
83 provider:
84 password: secret
85 server: lb.mydomain.com
86 user: admin
87 delegate_to: localhost
88
89 # Upload a directory of files
90 - name: Recursively upload web related files in /var/tmp/project
91 find:
92 paths: /var/tmp/project
93 patterns: "^.*?\\.(?:html|?:css|?:js)$"
94 use_regex: true
95 register: f
96
97 - name: Upload a directory of files as a set of iFiles
98 bigip_file_copy:
99 source: "{{ item.path }}"
100 datastore: ifile
101 provider:
102 password: secret
103 server: lb.mydomain.com
104 user: admin
105 loop: f
106 delegate_to: localhost
107 # End upload a directory of files
108
109 - name: Upload a file to use in an external monitor
110 bigip_file_copy:
111 source: /path/to/files/external.sh
112 datastore: external-monitor
113 provider:
114 password: secret
115 server: lb.mydomain.com
116 user: admin
117 delegate_to: localhost
118 '''
119
120 RETURN = r'''
121 # only common fields returned
122 '''
123
124 import hashlib
125 import os
126 from datetime import datetime
127
128 from ansible.module_utils.basic import (
129 AnsibleModule, env_fallback
130 )
131
132 from ..module_utils.bigip import F5RestClient
133 from ..module_utils.common import (
134 F5ModuleError, AnsibleF5Parameters, transform_name, f5_argument_spec
135 )
136 from ..module_utils.icontrol import (
137 upload_file, tmos_version
138 )
139 from ..module_utils.teem import send_teem
140
141
142 class Parameters(AnsibleF5Parameters):
143 api_map = {
144
145 }
146
147 api_attributes = [
148
149 ]
150
151 returnables = [
152
153 ]
154
155 updatables = [
156 'checksum',
157 ]
158
159
160 class ApiParameters(Parameters):
161 @property
162 def checksum(self):
163 """Returns a plain checksum value without the leading extra characters
164
165 Values are stored in the REST as the following.
166
167 ``"checksum": "SHA1:77002:b84015799949ac4acad87b81691455242a31e894"``
168
169 Returns:
170 string: The parsed SHA1 checksum.
171 """
172 if self._values['checksum'] is None:
173 return None
174 return str(self._values['checksum'].split(':')[2])
175
176
177 class ModuleParameters(Parameters):
178 @property
179 def checksum(self):
180 """Return SHA1 checksum of the file on disk
181
182 Returns:
183 string: The SHA1 checksum of the file.
184
185 References:
186 - https://stackoverflow.com/a/22058673/661215
187 """
188 if self._values['datastore'] == 'lw4o6-table':
189 return None
190
191 sha1 = hashlib.sha1()
192 with open(self._values['source'], 'rb') as f:
193 while True:
194 data = f.read(4096)
195 if not data:
196 break
197 sha1.update(data)
198 return sha1.hexdigest()
199
200 @property
201 def name(self):
202 if self._values['name'] is not None:
203 return self._values['name']
204 if self._values['source'] is None:
205 return None
206 return os.path.basename(self._values['source'])
207
208
209 class Changes(Parameters):
210 def to_return(self):
211 result = {}
212 try:
213 for returnable in self.returnables:
214 result[returnable] = getattr(self, returnable)
215 result = self._filter_params(result)
216 except Exception:
217 raise
218 return result
219
220
221 class UsableChanges(Changes):
222 pass
223
224
225 class ReportableChanges(Changes):
226 pass
227
228
229 class Difference(object):
230 def __init__(self, want, have=None):
231 self.want = want
232 self.have = have
233
234 def compare(self, param):
235 try:
236 result = getattr(self, param)
237 return result
238 except AttributeError:
239 return self.__default(param)
240
241 def __default(self, param):
242 attr1 = getattr(self.want, param)
243 try:
244 attr2 = getattr(self.have, param)
245 if attr1 != attr2:
246 return attr1
247 except AttributeError:
248 return attr1
249
250
251 class BaseManager(object):
252 def __init__(self, *args, **kwargs):
253 self.module = kwargs.get('module', None)
254 self.client = F5RestClient(**self.module.params)
255 self.want = ModuleParameters(params=self.module.params)
256 self.have = ApiParameters()
257 self.changes = UsableChanges()
258
259 def _set_changed_options(self):
260 changed = {}
261 for key in Parameters.returnables:
262 if getattr(self.want, key) is not None:
263 changed[key] = getattr(self.want, key)
264 if changed:
265 self.changes = UsableChanges(params=changed)
266
267 def _update_changed_options(self):
268 diff = Difference(self.want, self.have)
269 updatables = Parameters.updatables
270 changed = dict()
271 for k in updatables:
272 change = diff.compare(k)
273 if change is None:
274 continue
275 else:
276 if isinstance(change, dict):
277 changed.update(change)
278 else:
279 changed[k] = change
280 if changed:
281 self.changes = UsableChanges(params=changed)
282 return True
283 return False
284
285 def should_update(self):
286 result = self._update_changed_options()
287 if result:
288 return True
289 return False
290
291 def exec_module(self):
292 start = datetime.now().isoformat()
293 version = tmos_version(self.client)
294 changed = False
295 result = dict()
296 state = self.want.state
297
298 if state == "present":
299 changed = self.present()
300 elif state == "absent":
301 changed = self.absent()
302
303 reportable = ReportableChanges(params=self.changes.to_return())
304 changes = reportable.to_return()
305 result.update(**changes)
306 result.update(dict(changed=changed))
307 self._announce_deprecations(result)
308 send_teem(start, self.client, self.module, version)
309 return result
310
311 def _announce_deprecations(self, result):
312 warnings = result.pop('__warnings', [])
313 for warning in warnings:
314 self.client.module.deprecate(
315 msg=warning['msg'],
316 version=warning['version']
317 )
318
319 def present(self):
320 if self.exists():
321 return self.update()
322 else:
323 return self.create()
324
325 def update(self):
326 self.have = self.read_current_from_device()
327 if not self.should_update() and not self.want.force:
328 return False
329 if self.module.check_mode:
330 return True
331 self.remove_from_device()
332 self.upload_to_device()
333 self.create_on_device()
334 self.remove_uploaded_file_from_device(self.want.name)
335 return True
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 resource.")
343 return True
344
345 def create(self):
346 if self.module.check_mode:
347 return True
348 self.upload_to_device()
349 self.create_on_device()
350 self.remove_uploaded_file_from_device(self.want.name)
351 return True
352
353 def absent(self):
354 if self.exists():
355 return self.remove()
356 return False
357
358 def upload_to_device(self):
359 url = 'https://{0}:{1}/mgmt/shared/file-transfer/uploads'.format(
360 self.client.provider['server'],
361 self.client.provider['server_port']
362 )
363 try:
364 upload_file(self.client, url, self.want.source, self.want.name)
365 except F5ModuleError:
366 raise F5ModuleError(
367 "Failed to upload the file."
368 )
369
370 def remove_uploaded_file_from_device(self, name):
371 filepath = '/var/config/rest/downloads/{0}'.format(name)
372 params = {
373 "command": "run",
374 "utilCmdArgs": filepath
375 }
376 uri = "https://{0}:{1}/mgmt/tm/util/unix-rm".format(
377 self.client.provider['server'],
378 self.client.provider['server_port']
379 )
380 resp = self.client.api.post(uri, json=params)
381 try:
382 response = resp.json()
383 except ValueError as ex:
384 raise F5ModuleError(str(ex))
385
386 if resp.status in [200, 201] or 'code' in response and response['code'] in [200, 201]:
387 return True
388 raise F5ModuleError(resp.content)
389
390
391 class IFileManager(BaseManager):
392 def create_on_device(self):
393 params = self.changes.api_params()
394 params['name'] = self.want.name
395 params['source-path'] = 'file:/var/config/rest/downloads/{0}'.format(self.want.name)
396 params['partition'] = self.want.partition
397 uri = "https://{0}:{1}/mgmt/tm/sys/file/ifile/".format(
398 self.client.provider['server'],
399 self.client.provider['server_port']
400 )
401 resp = self.client.api.post(uri, json=params)
402 try:
403 response = resp.json()
404 except ValueError as ex:
405 raise F5ModuleError(str(ex))
406
407 if resp.status in [200, 201] or 'code' in response and response['code'] in [200, 201]:
408 return True
409 raise F5ModuleError(resp.content)
410
411 def exists(self):
412 uri = "https://{0}:{1}/mgmt/tm/sys/file/ifile/{2}".format(
413 self.client.provider['server'],
414 self.client.provider['server_port'],
415 transform_name(self.want.partition, self.want.name)
416 )
417 resp = self.client.api.get(uri)
418 try:
419 response = resp.json()
420 except ValueError as ex:
421 raise F5ModuleError(str(ex))
422
423 if resp.status == 404 or 'code' in response and response['code'] == 404:
424 return False
425 if resp.status in [200, 201] or 'code' in response and response['code'] in [200, 201]:
426 return True
427
428 errors = [401, 403, 409, 500, 501, 502, 503, 504]
429
430 if resp.status in errors or 'code' in response and response['code'] in errors:
431 if 'message' in response:
432 raise F5ModuleError(response['message'])
433 else:
434 raise F5ModuleError(resp.content)
435
436 def read_current_from_device(self):
437 uri = "https://{0}:{1}/mgmt/tm/sys/file/ifile/{2}".format(
438 self.client.provider['server'],
439 self.client.provider['server_port'],
440 transform_name(self.want.partition, self.want.name)
441 )
442 resp = self.client.api.get(uri)
443 try:
444 response = resp.json()
445 except ValueError as ex:
446 raise F5ModuleError(str(ex))
447
448 if resp.status in [200, 201] or 'code' in response and response['code'] in [200, 201]:
449 return ApiParameters(params=response)
450 raise F5ModuleError(resp.content)
451
452 def remove_from_device(self):
453 uri = "https://{0}:{1}/mgmt/tm/sys/file/ifile/{2}".format(
454 self.client.provider['server'],
455 self.client.provider['server_port'],
456 transform_name(self.want.partition, self.want.name)
457 )
458 response = self.client.api.delete(uri)
459 if response.status == 200:
460 return True
461 raise F5ModuleError(response.content)
462
463
464 class ExternalMonitorManager(BaseManager):
465 def create_on_device(self):
466 params = self.changes.api_params()
467 params['name'] = self.want.name
468 params['source-path'] = 'file:/var/config/rest/downloads/{0}'.format(self.want.name)
469 params['partition'] = self.want.partition
470 uri = "https://{0}:{1}/mgmt/tm/sys/file/external-monitor/".format(
471 self.client.provider['server'],
472 self.client.provider['server_port']
473 )
474 resp = self.client.api.post(uri, json=params)
475 try:
476 response = resp.json()
477 except ValueError as ex:
478 raise F5ModuleError(str(ex))
479
480 if 'code' in response and response['code'] in [400, 403]:
481 if 'message' in response:
482 raise F5ModuleError(response['message'])
483 else:
484 raise F5ModuleError(resp.content)
485
486 def exists(self):
487 uri = "https://{0}:{1}/mgmt/tm/sys/file/external-monitor/{2}".format(
488 self.client.provider['server'],
489 self.client.provider['server_port'],
490 transform_name(self.want.partition, self.want.name)
491 )
492 resp = self.client.api.get(uri)
493 try:
494 response = resp.json()
495 except ValueError as ex:
496 raise F5ModuleError(str(ex))
497
498 if resp.status == 404 or 'code' in response and response['code'] == 404:
499 return False
500 if resp.status in [200, 201] or 'code' in response and response['code'] in [200, 201]:
501 return True
502
503 errors = [401, 403, 409, 500, 501, 502, 503, 504]
504
505 if resp.status in errors or 'code' in response and response['code'] in errors:
506 if 'message' in response:
507 raise F5ModuleError(response['message'])
508 else:
509 raise F5ModuleError(resp.content)
510
511 def read_current_from_device(self):
512 uri = "https://{0}:{1}/mgmt/tm/sys/file/external-monitor/{2}".format(
513 self.client.provider['server'],
514 self.client.provider['server_port'],
515 transform_name(self.want.partition, self.want.name)
516 )
517 resp = self.client.api.get(uri)
518 try:
519 response = resp.json()
520 except ValueError as ex:
521 raise F5ModuleError(str(ex))
522
523 if resp.status in [200, 201] or 'code' in response and response['code'] in [200, 201]:
524 return ApiParameters(params=response)
525 raise F5ModuleError(resp.content)
526
527 def remove_from_device(self):
528 uri = "https://{0}:{1}/mgmt/tm/sys/file/external-monitor/{2}".format(
529 self.client.provider['server'],
530 self.client.provider['server_port'],
531 transform_name(self.want.partition, self.want.name)
532 )
533 response = self.client.api.delete(uri)
534 if response.status == 200:
535 return True
536 raise F5ModuleError(response.content)
537
538
539 class Lw4o6Manager(BaseManager):
540 def create_on_device(self):
541 params = self.changes.api_params()
542 params['name'] = self.want.name
543 params['source-path'] = 'file:/var/config/rest/downloads/{0}'.format(self.want.name)
544 params['partition'] = self.want.partition
545 uri = "https://{0}:{1}/mgmt/tm/sys/file/lwtunneltbl/".format(
546 self.client.provider['server'],
547 self.client.provider['server_port']
548 )
549 resp = self.client.api.post(uri, json=params)
550 try:
551 response = resp.json()
552 except ValueError as ex:
553 raise F5ModuleError(str(ex))
554
555 if 'code' in response and response['code'] in [400, 403]:
556 if 'message' in response:
557 raise F5ModuleError(response['message'])
558 else:
559 raise F5ModuleError(resp.content)
560
561 def exists(self):
562 uri = "https://{0}:{1}/mgmt/tm/sys/file/lwtunneltbl/{2}".format(
563 self.client.provider['server'],
564 self.client.provider['server_port'],
565 transform_name(self.want.partition, self.want.name)
566 )
567 resp = self.client.api.get(uri)
568 try:
569 response = resp.json()
570 except ValueError as ex:
571 raise F5ModuleError(str(ex))
572
573 if resp.status == 404 or 'code' in response and response['code'] == 404:
574 return False
575 if resp.status in [200, 201] or 'code' in response and response['code'] in [200, 201]:
576 return True
577
578 errors = [401, 403, 409, 500, 501, 502, 503, 504]
579
580 if resp.status in errors or 'code' in response and response['code'] in errors:
581 if 'message' in response:
582 raise F5ModuleError(response['message'])
583 else:
584 raise F5ModuleError(resp.content)
585
586 def read_current_from_device(self):
587 uri = "https://{0}:{1}/mgmt/tm/sys/file/lwtunneltbl/{2}".format(
588 self.client.provider['server'],
589 self.client.provider['server_port'],
590 transform_name(self.want.partition, self.want.name)
591 )
592 resp = self.client.api.get(uri)
593 try:
594 response = resp.json()
595 except ValueError as ex:
596 raise F5ModuleError(str(ex))
597
598 if resp.status in [200, 201] or 'code' in response and response['code'] in [200, 201]:
599 return ApiParameters(params=response)
600 raise F5ModuleError(resp.content)
601
602 def remove_from_device(self):
603 uri = "https://{0}:{1}/mgmt/tm/sys/file/lwtunneltbl/{2}".format(
604 self.client.provider['server'],
605 self.client.provider['server_port'],
606 transform_name(self.want.partition, self.want.name)
607 )
608 response = self.client.api.delete(uri)
609 if response.status == 200:
610 return True
611 raise F5ModuleError(response.content)
612
613
614 class ModuleManager(object):
615 def __init__(self, *args, **kwargs):
616 self.module = kwargs.get('module', None)
617 self.client = kwargs.get('client', None)
618 self.kwargs = kwargs
619
620 def exec_module(self):
621 if self.module.params['datastore'] == 'ifile':
622 manager = self.get_manager('v1')
623 elif self.module.params['datastore'] == 'external-monitor':
624 manager = self.get_manager('v2')
625 elif self.module.params['datastore'] == 'lw4o6-table':
626 manager = self.get_manager('v3')
627 else:
628 raise F5ModuleError(
629 "Unknown datastore specified."
630 )
631 return manager.exec_module()
632
633 def get_manager(self, type):
634 if type == 'v1':
635 return IFileManager(**self.kwargs)
636 elif type == 'v2':
637 return ExternalMonitorManager(**self.kwargs)
638 elif type == 'v3':
639 return Lw4o6Manager(**self.kwargs)
640
641
642 class ArgumentSpec(object):
643 def __init__(self):
644 self.supports_check_mode = True
645 argument_spec = dict(
646 name=dict(),
647 source=dict(
648 type='path',
649 aliases=['src'],
650 ),
651 datastore=dict(
652 choices=[
653 'external-monitor',
654 'ifile',
655 'lw4o6-table',
656 ],
657 default='ifile'
658 ),
659 force=dict(type='bool', default='no'),
660 state=dict(
661 default='present',
662 choices=['present', 'absent']
663 ),
664 partition=dict(
665 default='Common',
666 fallback=(env_fallback, ['F5_PARTITION'])
667 )
668 )
669 self.argument_spec = {}
670 self.argument_spec.update(f5_argument_spec)
671 self.argument_spec.update(argument_spec)
672 self.required_if = [
673 ['state', 'present', ['source']]
674 ]
675
676
677 def main():
678 spec = ArgumentSpec()
679
680 module = AnsibleModule(
681 argument_spec=spec.argument_spec,
682 supports_check_mode=spec.supports_check_mode,
683 required_if=spec.required_if,
684 )
685
686 try:
687 mm = ModuleManager(module=module)
688 results = mm.exec_module()
689 module.exit_json(**results)
690 except F5ModuleError as ex:
691 module.fail_json(msg=str(ex))
692
693
694 if __name__ == '__main__':
695 main()