Debian Codegraph @

ansible_collections/f5networks/f5_modules/plugins/modules/bigip_software_image.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_software_image
13 short_description: Manage software images on a BIG-IP
14 description:
15 - Manages software images on a BIG-IP. These images may include both base images
16 and hotfix images.
17 version_added: "1.0.0"
18 options:
19 force:
20 description:
21 - When C(true), uploads the file every time and replaces the file on the
22 device.
23 - When C(false), the file is only uploaded if it does not already
24 exist.
25 - Generally should be C(true) only in cases where you have reason
26 to believe the image was corrupted during upload.
27 type: bool
28 default: false
29 state:
30 description:
31 - When C(present), ensures the image is uploaded.
32 - When C(absent), ensures the image is removed.
33 type: str
34 choices:
35 - absent
36 - present
37 default: present
38 image:
39 description:
40 - The image to put on the remote device.
41 - This may be an absolute or relative location on the Ansible controller.
42 - Image names, whether they are base ISOs or hotfix ISOs, B(must) be unique.
43 type: str
44 required: True
45 extends_documentation_fragment: f5networks.f5_modules.f5
46 author:
47 - Tim Rupp (@caphrim007)
48 '''
49
50 EXAMPLES = r'''
51 - name: Upload relative image to the BIG-IP
52 bigip_software_image:
53 image: BIGIP-13.0.0.0.0.1645.iso
54 provider:
55 password: secret
56 server: lb.mydomain.com
57 user: admin
58 delegate_to: localhost
59
60 - name: Upload absolute image to the BIG-IP
61 bigip_software_image:
62 image: /path/to/images/BIGIP-13.0.0.0.0.1645.iso
63 provider:
64 password: secret
65 server: lb.mydomain.com
66 user: admin
67 delegate_to: localhost
68
69 - name: Upload image in a role to the BIG-IP
70 bigip_software_image:
71 image: "{{ role_path }}/files/BIGIP-13.0.0.0.0.1645.iso"
72 provider:
73 password: secret
74 server: lb.mydomain.com
75 user: admin
76 delegate_to: localhost
77 '''
78
79 RETURN = r'''
80 image_type:
81 description: Whether the image is a release or hotfix image.
82 returned: changed
83 type: str
84 sample: release
85 version:
86 description: Version of the software contained in the image.
87 returned: changed
88 type: str
89 sample: 13.1.0.8
90 build:
91 description: Build version of the software contained in the image.
92 returned: changed
93 type: str
94 sample: 0.0.3
95 checksum:
96 description: MD5 checksum of the ISO.
97 returned: changed
98 type: str
99 sample: 8cdbd094195fab4b2b47ff4285577b70
100 file_size:
101 description: Size of the uploaded image in MB.
102 returned: changed
103 type: int
104 sample: 1948
105 '''
106
107 import os
108 import time
109 from datetime import datetime
110
111 from ansible.module_utils.urls import urlparse
112 from ansible.module_utils.basic import AnsibleModule
113
114 from ..module_utils.bigip import F5RestClient
115 from ..module_utils.common import (
116 F5ModuleError, AnsibleF5Parameters, f5_argument_spec
117 )
118 from ..module_utils.icontrol import (
119 upload_file, tmos_version
120 )
121 from ..module_utils.teem import send_teem
122
123
124 class Parameters(AnsibleF5Parameters):
125 api_map = {
126 'fileSize': 'file_size'
127 }
128
129 api_attributes = [
130
131 ]
132
133 returnables = [
134 'image_type',
135 'version',
136 'build',
137 'checksum',
138 'file_size',
139 ]
140
141 updatables = [
142
143 ]
144
145
146 class ApiParameters(Parameters):
147 @property
148 def file_size(self):
149 if self._values['file_size'] is None:
150 return None
151 tmp = self._values['file_size'].split(' ')
152 return int(tmp[0])
153
154
155 class ModuleParameters(Parameters):
156 @property
157 def filename(self):
158 return os.path.basename(self.image)
159
160
161 class Changes(Parameters):
162 def to_return(self):
163 result = {}
164 try:
165 for returnable in self.returnables:
166 result[returnable] = getattr(self, returnable)
167 result = self._filter_params(result)
168 except Exception:
169 pass
170 return result
171
172
173 class UsableChanges(Changes):
174 pass
175
176
177 class ReportableChanges(Changes):
178 pass
179
180
181 class Difference(object):
182 def __init__(self, want, have=None):
183 self.want = want
184 self.have = have
185
186 def compare(self, param):
187 try:
188 result = getattr(self, param)
189 return result
190 except AttributeError:
191 return self.__default(param)
192
193 def __default(self, param):
194 attr1 = getattr(self.want, param)
195 try:
196 attr2 = getattr(self.have, param)
197 if attr1 != attr2:
198 return attr1
199 except AttributeError:
200 return attr1
201
202
203 class ModuleManager(object):
204 def __init__(self, *args, **kwargs):
205 self.module = kwargs.get('module', None)
206 self.client = F5RestClient(**self.module.params)
207 self.want = ModuleParameters(params=self.module.params)
208 self.have = ApiParameters()
209 self.changes = UsableChanges()
210 self.image_type = None
211 self.image_url = None
212
213 def _set_changed_options(self):
214 changed = {}
215 for key in Parameters.returnables:
216 if getattr(self.want, key) is not None:
217 changed[key] = getattr(self.want, key)
218 if changed:
219 self.changes = UsableChanges(params=changed)
220
221 def _update_changed_options(self):
222 diff = Difference(self.want, self.have)
223 updatables = Parameters.updatables
224 changed = dict()
225 for k in updatables:
226 change = diff.compare(k)
227 if change is None:
228 continue
229 else:
230 if isinstance(change, dict):
231 changed.update(change)
232 else:
233 changed[k] = change
234 if changed:
235 self.changes = UsableChanges(params=changed)
236 return True
237 return False
238
239 def should_update(self):
240 result = self._update_changed_options()
241 if result:
242 return True
243 return False
244
245 def exec_module(self):
246 start = datetime.now().isoformat()
247 version = tmos_version(self.client)
248 changed = False
249 result = dict()
250 state = self.want.state
251
252 if state == "present":
253 changed = self.present()
254 elif state == "absent":
255 changed = self.absent()
256
257 reportable = ReportableChanges(params=self.changes.to_return())
258 changes = reportable.to_return()
259 result.update(**changes)
260 result.update(dict(changed=changed))
261 self._announce_deprecations(result)
262 send_teem(start, self.client, self.module, version)
263 return result
264
265 def _announce_deprecations(self, result):
266 warnings = result.pop('__warnings', [])
267 for warning in warnings:
268 self.client.module.deprecate(
269 msg=warning['msg'],
270 version=warning['version']
271 )
272
273 def present(self):
274 if self.exists():
275 return self.update()
276 else:
277 return self.create()
278
279 def exists(self):
280 if self.image_exists() or self.hotfix_exists():
281 return True
282 return False
283
284 def _set_image_url(self, item):
285 path = urlparse(item['selfLink']).path
286 self.image_url = "https://{0}:{1}{2}".format(
287 self.client.provider['server'],
288 self.client.provider['server_port'],
289 path
290 )
291
292 def image_exists(self):
293 result = False
294 uri = "https://{0}:{1}/mgmt/tm/sys/software/image/".format(
295 self.client.provider['server'],
296 self.client.provider['server_port'],
297 )
298 resp = self.client.api.get(uri)
299
300 try:
301 response = resp.json()
302 except ValueError as ex:
303 raise F5ModuleError(str(ex))
304
305 errors = [401, 403, 409, 500, 501, 502, 503, 504]
306
307 if resp.status in errors or 'code' in response and response['code'] in errors:
308 if 'message' in response:
309 raise F5ModuleError(response['message'])
310 else:
311 raise F5ModuleError(resp.content)
312
313 if 'items' in response:
314 for item in response['items']:
315 if item['name'].startswith(self.want.filename):
316 self._set_image_url(item)
317 self.image_type = 'release'
318 result = True
319 break
320 return result
321
322 def hotfix_exists(self):
323 result = False
324 uri = "https://{0}:{1}/mgmt/tm/sys/software/hotfix/".format(
325 self.client.provider['server'],
326 self.client.provider['server_port'],
327 )
328 resp = self.client.api.get(uri)
329
330 try:
331 response = resp.json()
332 except ValueError as ex:
333 raise F5ModuleError(str(ex))
334
335 errors = [401, 403, 409, 500, 501, 502, 503, 504]
336
337 if resp.status in errors or 'code' in response and response['code'] in errors:
338 if 'message' in response:
339 raise F5ModuleError(response['message'])
340 else:
341 raise F5ModuleError(resp.content)
342
343 if 'items' in response:
344 for item in response['items']:
345 if item['name'].startswith(self.want.filename):
346 self._set_image_url(item)
347 self.image_type = 'hotfix'
348 result = True
349 break
350 return result
351
352 def update(self):
353 if self.module.check_mode:
354 return True
355 if self.want.force:
356 # The process of updating is a forced re-creation.
357 self.remove_from_device()
358 self.create_on_device()
359 return True
360 return False
361
362 def remove(self):
363 if self.module.check_mode:
364 return True
365 self.remove_from_device()
366
367 # Deleting images involves a short period of inconsistency in the REST
368 # API due to needing to remove files from disk and update MCPD.
369 #
370 # This should not (realistically) take more than 30 seconds.
371 for x in range(0, 30):
372 if not self.exists():
373 return True
374 time.sleep(1)
375 raise F5ModuleError("Failed to delete the resource.")
376
377 def _set_mode_and_ownership(self):
378 url = 'https://{0}:{1}/mgmt/tm/util/bash'.format(
379 self.client.provider['server'],
380 self.client.provider['server_port']
381 )
382 ownership = 'root:root'
383 image_path = '/shared/images/{0}'.format(self.want.filename)
384 file_mode = '0644'
385 args = dict(
386 command='run',
387 utilCmdArgs='-c "chown {0} {1};chmod {2} {1}"'.format(ownership, image_path, file_mode)
388 )
389
390 self.client.api.post(url, json=args)
391
392 def create(self):
393 self._set_changed_options()
394 if self.module.check_mode:
395 return True
396
397 self.create_on_device()
398
399 # Creating images involves a short period of inconsistency in the REST
400 # API likely due to having to move files into appropriate places on disk
401 # and update MCPD with information.
402 #
403 # This should not (realistically) take more than 30 seconds.
404 for x in range(0, 30):
405 if self.exists():
406 # We want to return some information about the image that was just uploaded
407 #
408 # This must appear after the creation process because the information
409 # does not exist on the device (has been parsed by BIG-IP) until the
410 # ISO is uploaded.
411 self._set_mode_and_ownership()
412 self.want = self.read_current_from_device()
413 self._set_changed_options()
414 return True
415 time.sleep(1)
416 raise F5ModuleError("Failed to create the resource.")
417
418 def create_on_device(self):
419 url = 'https://{0}:{1}/mgmt/cm/autodeploy/software-image-uploads'.format(
420 self.client.provider['server'],
421 self.client.provider['server_port']
422 )
423 try:
424 upload_file(self.client, url, self.want.image)
425 except F5ModuleError:
426 raise
427
428 def read_current_from_device(self):
429 resp = self.client.api.get(self.image_url)
430 try:
431 response = resp.json()
432 except ValueError as ex:
433 raise F5ModuleError(str(ex))
434
435 if 'code' in response and response['code'] in [400, 404]:
436 if 'message' in response:
437 raise F5ModuleError(response['message'])
438 else:
439 raise F5ModuleError(resp.content)
440 result = ApiParameters(params=response)
441 result.update({'image_type': self.image_type})
442 return result
443
444 def absent(self):
445 if self.exists():
446 return self.remove()
447 return False
448
449 def remove_from_device(self):
450 if self.image_exists():
451 self.remove_iso_from_device('image')
452 elif self.hotfix_exists():
453 self.remove_iso_from_device('hotfix')
454
455 def remove_iso_from_device(self, type):
456 uri = "https://{0}:{1}/mgmt/tm/sys/software/{2}/{3}".format(
457 self.client.provider['server'],
458 self.client.provider['server_port'],
459 type,
460 self.want.filename
461 )
462 response = self.client.api.delete(uri)
463 if response.status == 200:
464 return True
465 if 'code' in response and response['code'] in [400, 404]:
466 if 'message' in response:
467 raise F5ModuleError(response['message'])
468 else:
469 raise F5ModuleError(response.content)
470
471
472 class ArgumentSpec(object):
473 def __init__(self):
474 self.supports_check_mode = True
475 argument_spec = dict(
476 force=dict(type='bool', default='no'),
477 image=dict(required=True),
478 state=dict(
479 default='present',
480 choices=['present', 'absent']
481 ),
482 )
483 self.argument_spec = {}
484 self.argument_spec.update(f5_argument_spec)
485 self.argument_spec.update(argument_spec)
486
487
488 def main():
489 spec = ArgumentSpec()
490
491 module = AnsibleModule(
492 argument_spec=spec.argument_spec,
493 supports_check_mode=spec.supports_check_mode
494 )
495
496 try:
497 mm = ModuleManager(module=module)
498 results = mm.exec_module()
499 module.exit_json(**results)
500 except F5ModuleError as ex:
501 module.fail_json(msg=str(ex))
502
503
504 if __name__ == '__main__':
505 main()