Debian Codegraph @

ansible_collections/f5networks/f5_modules/plugins/modules/bigip_apm_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_apm_policy_fetch
13 short_description: Exports the APM policy or APM access profile from remote nodes.
14 description:
15 - Exports the APM policy or APM access profile from remote nodes.
16 version_added: "1.0.0"
17 options:
18 name:
19 description:
20 - The name of the APM policy or APM access profile 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 file into.
26 type: path
27 file:
28 description:
29 - The name of the file to be created on the remote device for downloading.
30 type: str
31 type:
32 description:
33 - Specifies the type of item to export from the device.
34 type: str
35 choices:
36 - profile_access
37 - access_policy
38 default: profile_access
39 force:
40 description:
41 - If C(false), the file will only be transferred if it does not exist in the the destination.
42 type: bool
43 default: true
44 partition:
45 description:
46 - Device partition which contains the APM policy or APM access profile to export.
47 type: str
48 default: Common
49 notes:
50 - Due to ID685681 it is not possible to execute ng_* tools via REST API on v12.x and 13.x, once this is fixed
51 this restriction will be removed.
52 - Requires BIG-IP >= 14.0.0
53 extends_documentation_fragment: f5networks.f5_modules.f5
54 author:
55 - Wojciech Wypior (@wojtek0806)
56 '''
57
58 EXAMPLES = r'''
59 - name: Export APM access profile
60 bigip_apm_policy_fetch:
61 name: foobar
62 file: export_foo
63 dest: /root/download
64 provider:
65 password: secret
66 server: lb.mydomain.com
67 user: admin
68 delegate_to: localhost
69
70 - name: Export APM access policy
71 bigip_apm_policy_fetch:
72 name: foobar
73 file: export_foo
74 dest: /root/download
75 type: access_policy
76 provider:
77 password: secret
78 server: lb.mydomain.com
79 user: admin
80 delegate_to: localhost
81
82 - name: Export APM access profile, autogenerate name
83 bigip_apm_policy_fetch:
84 name: foobar
85 dest: /root/download
86 provider:
87 password: secret
88 server: lb.mydomain.com
89 user: admin
90 delegate_to: localhost
91 '''
92
93 RETURN = r'''
94 name:
95 description: Name of the APM policy or APM access profile to be exported.
96 returned: changed
97 type: str
98 sample: APM_policy_global
99 file:
100 description:
101 - Name of the exported file on the remote BIG-IP to download. If not
102 specified, then this will be a randomly generated filename.
103 returned: changed
104 type: str
105 sample: foobar_file
106 dest:
107 description: Local path to download the exported APM policy.
108 returned: changed
109 type: str
110 sample: /root/downloads/profile-foobar_file.conf.tar.gz
111 type:
112 description: Set to specify the type of item to export.
113 returned: changed
114 type: str
115 sample: access_policy
116 '''
117
118 import os
119 import tempfile
120 import traceback
121 from datetime import datetime
122
123 try:
124 from packaging.version import Version
125 except ImportError:
126 HAS_PACKAGING = False
127 Version = None
128 PACKAGING_IMPORT_ERROR = traceback.format_exc()
129 else:
130 HAS_PACKAGING = True
131 PACKAGING_IMPORT_ERROR = None
132
133 from ansible.module_utils.basic import (
134 AnsibleModule, missing_required_lib, env_fallback
135 )
136
137 from ..module_utils.bigip import F5RestClient
138 from ..module_utils.common import (
139 F5ModuleError, AnsibleF5Parameters, transform_name, f5_argument_spec
140 )
141 from ..module_utils.icontrol import (
142 module_provisioned, tmos_version, download_file
143 )
144 from ..module_utils.teem import send_teem
145
146
147 class Parameters(AnsibleF5Parameters):
148 api_map = {}
149
150 api_attributes = []
151
152 returnables = [
153 'name',
154 'file',
155 'dest',
156 'type',
157 'force',
158 ]
159
160 updatables = []
161
162
163 class ApiParameters(Parameters):
164 pass
165
166
167 class ModuleParameters(Parameters):
168 @property
169 def file(self):
170 if self._values['file'] is not None:
171 return self._values['file']
172 result = next(tempfile._get_candidate_names()) + '.tar.gz'
173 self._values['file'] = result
174 return result
175
176 @property
177 def fulldest(self):
178 if os.path.isdir(self.dest):
179 result = os.path.join(self.dest, self.file)
180 else:
181 if os.path.exists(os.path.dirname(self.dest)):
182 result = self.dest
183 else:
184 try:
185 # os.path.exists() can return false in some
186 # circumstances where the directory does not have
187 # the execute bit for the current user set, in
188 # which case the stat() call will raise an OSError
189 result = self.dest
190 os.stat(os.path.dirname(result))
191 except OSError as e:
192 if "permission denied" in str(e).lower():
193 raise F5ModuleError(
194 "Destination directory {0} is not accessible".format(os.path.dirname(self.dest))
195 )
196 raise F5ModuleError(
197 "Destination directory {0} does not exist".format(os.path.dirname(self.dest))
198 )
199
200 if not os.access(os.path.dirname(result), os.W_OK):
201 raise F5ModuleError(
202 "Destination {0} not writable".format(os.path.dirname(result))
203 )
204 return result
205
206
207 class Changes(Parameters):
208 def to_return(self):
209 result = {}
210 try:
211 for returnable in self.returnables:
212 result[returnable] = getattr(self, returnable)
213 result = self._filter_params(result)
214 except Exception:
215 raise
216 return result
217
218
219 class UsableChanges(Changes):
220 pass
221
222
223 class ReportableChanges(Changes):
224 pass
225
226
227 class ModuleManager(object):
228 def __init__(self, *args, **kwargs):
229 self.module = kwargs.get('module', None)
230 self.client = F5RestClient(**self.module.params)
231 self.want = ModuleParameters(params=self.module.params)
232 self.changes = UsableChanges()
233
234 def _set_changed_options(self):
235 changed = {}
236 for key in Parameters.returnables:
237 if getattr(self.want, key) is not None:
238 changed[key] = getattr(self.want, key)
239 if changed:
240 self.changes = UsableChanges(params=changed)
241
242 def _announce_deprecations(self, result):
243 warnings = result.pop('__warnings', [])
244 for warning in warnings:
245 self.client.module.deprecate(
246 msg=warning['msg'],
247 version=warning['version']
248 )
249
250 def exec_module(self):
251 start = datetime.now().isoformat()
252 version = tmos_version(self.client)
253 if not module_provisioned(self.client, 'apm'):
254 raise F5ModuleError(
255 "APM must be provisioned to use this module."
256 )
257
258 if self.version_less_than_14():
259 raise F5ModuleError('Due to bug ID685681 it is not possible to use this module on TMOS version below 14.x')
260
261 result = dict()
262
263 self.export()
264
265 reportable = ReportableChanges(params=self.changes.to_return())
266 changes = reportable.to_return()
267 result.update(**changes)
268 result.update(dict(changed=True))
269 send_teem(start, self.client, self.module, version)
270 return result
271
272 def version_less_than_14(self):
273 version = tmos_version(self.client)
274 if Version(version) < Version('14.0.0'):
275 return True
276 return False
277
278 def export(self):
279 if self.exists():
280 return self.update()
281 else:
282 return self.create()
283
284 def update(self):
285 if not self.want.force:
286 raise F5ModuleError(
287 "File '{0}' already exists.".format(self.want.fulldest)
288 )
289 self.create_on_device()
290 self.execute()
291
292 def create(self):
293 self._set_changed_options()
294 if self.module.check_mode:
295 return True
296 self.create_on_device()
297 self.execute()
298 return True
299
300 def download(self):
301 self.download_from_device(self.want.fulldest)
302 if os.path.exists(self.want.fulldest):
303 return True
304 raise F5ModuleError(
305 "Failed to download the remote file."
306 )
307
308 def execute(self):
309 self.download()
310 self.remove_temp_file_from_device()
311 return True
312
313 def exists(self):
314 self.policy_exists()
315 if os.path.exists(self.want.fulldest):
316 return True
317 return False
318
319 def policy_exists(self):
320 errors = [401, 403, 409, 500, 501, 502, 503, 504]
321 if self.want.type == 'access_policy':
322 uri = 'https://{0}:{1}/mgmt/tm/apm/policy/access-policy/{2}'.format(
323 self.client.provider['server'],
324 self.client.provider['server_port'],
325 transform_name(self.want.partition, self.want.name)
326 )
327 else:
328 uri = 'https://{0}:{1}/mgmt/tm/apm/profile/access/{2}'.format(
329 self.client.provider['server'],
330 self.client.provider['server_port'],
331 transform_name(self.want.partition, self.want.name)
332 )
333 resp = self.client.api.get(uri)
334
335 try:
336 response = resp.json()
337 except ValueError as ex:
338 raise F5ModuleError(str(ex))
339
340 if resp.status == 404 or 'code' in response and response['code'] == 404:
341 raise F5ModuleError('The provided {0} with the name {1} does not exist on device.'.format(
342 self.want.type, self.want.name)
343 )
344
345 if resp.status in [200, 201] or 'code' in response and response['code'] in [200, 201]:
346 return True
347
348 if resp.status in errors or 'code' in response and response['code'] in errors:
349 if 'message' in response:
350 raise F5ModuleError(response['message'])
351 else:
352 raise F5ModuleError(resp.content)
353
354 def create_on_device(self):
355 cmd = 'ng_export -t {0} {1} {1} -p {2}'.format(
356 self.want.type, self.want.name, self.want.partition
357 )
358 uri = "https://{0}:{1}/mgmt/tm/util/bash/".format(
359 self.client.provider['server'],
360 self.client.provider['server_port'],
361 )
362 args = dict(
363 command='run',
364 utilCmdArgs='-c "{0}"'.format(cmd)
365 )
366 resp = self.client.api.post(uri, json=args)
367
368 try:
369 response = resp.json()
370 except ValueError as ex:
371 raise F5ModuleError(str(ex))
372
373 if 'commandResult' in response:
374 raise F5ModuleError('Item export command failed.')
375
376 if resp.status not in [200, 201] or 'code' in response and response['code'] not in [200, 201]:
377 raise F5ModuleError(resp.content)
378
379 self._move_file_to_download()
380
381 return True
382
383 def _move_file_to_download(self):
384 if self.want.type == 'access_policy':
385 item = 'policy'
386 else:
387 item = 'profile'
388
389 name = '{0}-{1}.conf.tar.gz'.format(item, self.want.name)
390 move_path = '/shared/tmp/{0} {1}/{2}'.format(
391 name,
392 '/shared/images',
393 self.want.file
394 )
395 params = dict(
396 command='run',
397 utilCmdArgs=move_path
398 )
399
400 uri = "https://{0}:{1}/mgmt/tm/util/unix-mv/".format(
401 self.client.provider['server'],
402 self.client.provider['server_port']
403 )
404
405 resp = self.client.api.post(uri, json=params)
406
407 try:
408 response = resp.json()
409 if 'commandResult' in response:
410 if 'cannot stat' in response['commandResult']:
411 raise F5ModuleError(response['commandResult'])
412 except ValueError as ex:
413 raise F5ModuleError(str(ex))
414
415 if resp.status in [200, 201] or 'code' in response and response['code'] in [200, 201]:
416 return True
417 raise F5ModuleError(resp.content)
418
419 def download_from_device(self, dest):
420 url = 'https://{0}:{1}/mgmt/cm/autodeploy/software-image-downloads/{2}'.format(
421 self.client.provider['server'],
422 self.client.provider['server_port'],
423 self.want.file
424 )
425 try:
426 download_file(self.client, url, dest)
427 except F5ModuleError:
428 raise F5ModuleError(
429 "Failed to download the file."
430 )
431 if os.path.exists(self.want.dest):
432 return True
433 return False
434
435 def remove_temp_file_from_device(self):
436 tpath_name = '/shared/images/{0}'.format(self.want.file)
437 uri = "https://{0}:{1}/mgmt/tm/util/unix-rm/".format(
438 self.client.provider['server'],
439 self.client.provider['server_port'],
440 )
441 args = dict(
442 command='run',
443 utilCmdArgs=tpath_name
444 )
445 resp = self.client.api.post(uri, json=args)
446 try:
447 response = resp.json()
448 except ValueError as ex:
449 raise F5ModuleError(str(ex))
450
451 if resp.status in [200, 201] or 'code' in response and response['code'] in [200, 201]:
452 return True
453 raise F5ModuleError(resp.content)
454
455
456 class ArgumentSpec(object):
457 def __init__(self):
458 self.supports_check_mode = True
459 argument_spec = dict(
460 name=dict(
461 required=True,
462 ),
463 dest=dict(
464 type='path'
465 ),
466 type=dict(
467 default='profile_access',
468 choices=['profile_access', 'access_policy']
469 ),
470 file=dict(),
471 force=dict(
472 default='yes',
473 type='bool'
474 ),
475 partition=dict(
476 default='Common',
477 fallback=(env_fallback, ['F5_PARTITION'])
478 )
479 )
480 self.argument_spec = {}
481 self.argument_spec.update(f5_argument_spec)
482 self.argument_spec.update(argument_spec)
483
484
485 def main():
486 spec = ArgumentSpec()
487
488 module = AnsibleModule(
489 argument_spec=spec.argument_spec,
490 supports_check_mode=spec.supports_check_mode,
491 )
492
493 if not HAS_PACKAGING:
494 module.fail_json(
495 msg=missing_required_lib('packaging'),
496 exception=PACKAGING_IMPORT_ERROR
497 )
498
499 try:
500 mm = ModuleManager(module=module)
501 results = mm.exec_module()
502 module.exit_json(**results)
503 except F5ModuleError as ex:
504 module.fail_json(msg=str(ex))
505
506
507 if __name__ == '__main__':
508 main()