Debian Codegraph @

ansible_collections/f5networks/f5_modules/plugins/modules/bigip_partition.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_partition
13 short_description: Manage BIG-IP partitions
14 description:
15 - Manage partitions on the BIG-IP.
16 version_added: "1.0.0"
17 options:
18 name:
19 description:
20 - Name of the partition.
21 type: str
22 required: True
23 description:
24 description:
25 - The description to attach to the partition.
26 type: str
27 route_domain:
28 description:
29 - The default Route Domain to assign to the partition. If no route domain
30 is specified, the default route domain for the system (typically
31 zero) will be used only when creating a new partition.
32 type: int
33 state:
34 description:
35 - Whether the partition should exist or not.
36 type: str
37 choices:
38 - present
39 - absent
40 default: present
41 notes:
42 - Requires BIG-IP software version >= 12
43 extends_documentation_fragment: f5networks.f5_modules.f5
44 author:
45 - Tim Rupp (@caphrim007)
46 - Wojciech Wypior (@wojtek0806)
47 '''
48
49 EXAMPLES = r'''
50 - name: Create partition "foo" using the default route domain
51 bigip_partition:
52 name: foo
53 provider:
54 password: secret
55 server: lb.mydomain.com
56 user: admin
57 delegate_to: localhost
58
59 - name: Create partition "bar" using a custom route domain
60 bigip_partition:
61 name: bar
62 route_domain: 3
63 provider:
64 password: secret
65 server: lb.mydomain.com
66 user: admin
67 delegate_to: localhost
68
69 - name: Change route domain of partition "foo"
70 bigip_partition:
71 name: foo
72 route_domain: 8
73 provider:
74 password: secret
75 server: lb.mydomain.com
76 user: admin
77 delegate_to: localhost
78
79 - name: Set a description for partition "foo"
80 bigip_partition:
81 name: foo
82 description: Tenant CompanyA
83 provider:
84 password: secret
85 server: lb.mydomain.com
86 user: admin
87 delegate_to: localhost
88
89 - name: Delete the "foo" partition
90 bigip_partition:
91 name: foo
92 state: absent
93 provider:
94 password: secret
95 server: lb.mydomain.com
96 user: admin
97 delegate_to: localhost
98 '''
99
100 RETURN = r'''
101 route_domain:
102 description: Name of the route domain associated with the partition.
103 returned: changed and success
104 type: int
105 sample: 0
106 description:
107 description: The description of the partition.
108 returned: changed and success
109 type: str
110 sample: Example partition
111 '''
112 from datetime import datetime
113
114 from ansible.module_utils.basic import AnsibleModule
115
116 from ..module_utils.bigip import F5RestClient
117 from ..module_utils.common import (
118 F5ModuleError, AnsibleF5Parameters, f5_argument_spec
119 )
120 from ..module_utils.compare import cmp_str_with_none
121 from ..module_utils.icontrol import tmos_version
122 from ..module_utils.teem import send_teem
123
124
125 class Parameters(AnsibleF5Parameters):
126 api_map = {
127 'defaultRouteDomain': 'route_domain',
128 }
129
130 api_attributes = [
131 'description',
132 'defaultRouteDomain',
133 ]
134
135 returnables = [
136 'description',
137 'route_domain',
138 'folder_description',
139 ]
140
141 updatables = [
142 'description',
143 'route_domain',
144 'folder_description',
145 ]
146
147
148 class ApiParameters(Parameters):
149 @property
150 def description(self):
151 if self._values['description'] in [None, 'none']:
152 return None
153 return self._values['description']
154
155
156 class ModuleParameters(Parameters):
157 @property
158 def partition(self):
159 # Cannot create a partition in a partition, so nullify this
160 return None
161
162 @property
163 def route_domain(self):
164 if self._values['route_domain'] is None:
165 return None
166 return int(self._values['route_domain'])
167
168 @property
169 def description(self):
170 if self._values['description'] is None:
171 return None
172 elif self._values['description'] in ['none', '']:
173 return ''
174 return self._values['description']
175
176
177 class Changes(Parameters):
178 def to_return(self):
179 result = {}
180 try:
181 for returnable in self.returnables:
182 result[returnable] = getattr(self, returnable)
183 result = self._filter_params(result)
184 except Exception:
185 pass
186 return result
187
188
189 class UsableChanges(Changes):
190 pass
191
192
193 class ReportableChanges(Changes):
194 pass
195
196
197 class Difference(object):
198 def __init__(self, want, have=None):
199 self.want = want
200 self.have = have
201
202 def compare(self, param):
203 try:
204 result = getattr(self, param)
205 return result
206 except AttributeError:
207 result = self.__default(param)
208 return result
209
210 def __default(self, param):
211 attr1 = getattr(self.want, param)
212 try:
213 attr2 = getattr(self.have, param)
214 if attr1 != attr2:
215 return attr1
216 except AttributeError:
217 return attr1
218
219 @property
220 def description(self):
221 if cmp_str_with_none(self.want.description, self.have.description) is None:
222 return cmp_str_with_none(self.want.description, self.have.folder_description)
223 else:
224 return self.want.description
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.have = ApiParameters()
233 self.changes = UsableChanges()
234
235 def _announce_deprecations(self, result):
236 warnings = result.pop('__warnings', [])
237 for warning in warnings:
238 self.client.module.deprecate(
239 msg=warning['msg'],
240 version=warning['version']
241 )
242
243 def _set_changed_options(self):
244 changed = {}
245 for key in Parameters.returnables:
246 if getattr(self.want, key) is not None:
247 changed[key] = getattr(self.want, key)
248 if changed:
249 self.changes = UsableChanges(params=changed)
250
251 def _update_changed_options(self):
252 diff = Difference(self.want, self.have)
253 updatables = Parameters.updatables
254 changed = dict()
255 for k in updatables:
256 change = diff.compare(k)
257 if change is None:
258 continue
259 else:
260 if isinstance(change, dict):
261 changed.update(change)
262 else:
263 changed[k] = change
264 if changed:
265 self.changes = UsableChanges(params=changed)
266 return True
267 return False
268
269 def exec_module(self):
270 start = datetime.now().isoformat()
271 version = tmos_version(self.client)
272 changed = False
273 result = dict()
274 state = self.want.state
275
276 if state == "present":
277 changed = self.present()
278 elif state == "absent":
279 changed = self.absent()
280
281 reportable = ReportableChanges(params=self.changes.to_return())
282 changes = reportable.to_return()
283 result.update(**changes)
284 result.update(dict(changed=changed))
285 self._announce_deprecations(result)
286 send_teem(start, self.client, self.module, version)
287 return result
288
289 def present(self):
290 if self.exists():
291 return self.update()
292 else:
293 return self.create()
294
295 def create(self):
296 self._set_changed_options()
297 if self.module.check_mode:
298 return True
299 self.create_on_device()
300 if self.changes.description:
301 self.update_folder_on_device()
302 if not self.exists():
303 raise F5ModuleError("Failed to create the partition.")
304 return True
305
306 def should_update(self):
307 result = self._update_changed_options()
308 if result:
309 return True
310 return False
311
312 def update(self):
313 self.have = self.read_current_from_device()
314 if not self.should_update():
315 return False
316 if self.module.check_mode:
317 return True
318 self.update_on_device()
319 if self.changes.description:
320 self.update_folder_on_device()
321 return True
322
323 def absent(self):
324 if self.exists():
325 return self.remove()
326 return False
327
328 def remove(self):
329 if self.module.check_mode:
330 return True
331 self.remove_from_device()
332 if self.exists():
333 raise F5ModuleError("Failed to delete the partition.")
334 return True
335
336 def read_current_from_device(self):
337 uri = "https://{0}:{1}/mgmt/tm/auth/partition/{2}".format(
338 self.client.provider['server'],
339 self.client.provider['server_port'],
340 self.want.name
341 )
342 resp = self.client.api.get(uri)
343 try:
344 response = resp.json()
345 except ValueError as ex:
346 raise F5ModuleError(str(ex))
347
348 if 'code' in response and response['code'] == 400:
349 if 'message' in response:
350 raise F5ModuleError(response['message'])
351 else:
352 raise F5ModuleError(resp.content)
353 result = ApiParameters(params=response)
354 uri = "https://{0}:{1}/mgmt/tm/sys/folder/~{2}".format(
355 self.client.provider['server'],
356 self.client.provider['server_port'],
357 self.want.name
358 )
359 resp = self.client.api.get(uri)
360 try:
361 response = resp.json()
362 except ValueError as ex:
363 raise F5ModuleError(str(ex))
364
365 if 'code' in response and response['code'] == 400:
366 if 'message' in response:
367 raise F5ModuleError(response['message'])
368 else:
369 raise F5ModuleError(resp.content)
370 result.update({'folder_description': response.get('description', None)})
371 return result
372
373 def exists(self):
374 uri = "https://{0}:{1}/mgmt/tm/auth/partition/{2}".format(
375 self.client.provider['server'],
376 self.client.provider['server_port'],
377 self.want.name
378 )
379 resp = self.client.api.get(uri)
380 try:
381 response = resp.json()
382 except ValueError as ex:
383 raise F5ModuleError(str(ex))
384
385 if resp.status == 404 or 'code' in response and response['code'] == 404:
386 return False
387 if resp.status in [200, 201] or 'code' in response and response['code'] in [200, 201]:
388 return True
389
390 errors = [401, 403, 409, 500, 501, 502, 503, 504]
391
392 if resp.status in errors or 'code' in response and response['code'] in errors:
393 if 'message' in response:
394 raise F5ModuleError(response['message'])
395 else:
396 raise F5ModuleError(resp.content)
397
398 def create_on_device(self):
399 params = self.changes.api_params()
400 params['name'] = self.want.name
401 uri = "https://{0}:{1}/mgmt/tm/auth/partition/".format(
402 self.client.provider['server'],
403 self.client.provider['server_port'],
404 )
405 resp = self.client.api.post(uri, json=params)
406 try:
407 response = resp.json()
408 except ValueError as ex:
409 raise F5ModuleError(str(ex))
410
411 if 'code' in response and response['code'] in [400, 403, 409]:
412 if 'message' in response:
413 raise F5ModuleError(response['message'])
414 else:
415 raise F5ModuleError(resp.content)
416
417 def update_on_device(self):
418 params = self.changes.api_params()
419 uri = "https://{0}:{1}/mgmt/tm/auth/partition/{2}".format(
420 self.client.provider['server'],
421 self.client.provider['server_port'],
422 self.want.name
423 )
424 resp = self.client.api.patch(uri, json=params)
425 try:
426 response = resp.json()
427 except ValueError as ex:
428 raise F5ModuleError(str(ex))
429
430 if 'code' in response and response['code'] == 400:
431 if 'message' in response:
432 raise F5ModuleError(response['message'])
433 else:
434 raise F5ModuleError(resp.content)
435
436 def update_folder_on_device(self):
437 params = dict(description=self.changes.description)
438 uri = "https://{0}:{1}/mgmt/tm/sys/folder/~{2}".format(
439 self.client.provider['server'],
440 self.client.provider['server_port'],
441 self.want.name
442 )
443 resp = self.client.api.patch(uri, json=params)
444 try:
445 response = resp.json()
446 except ValueError as ex:
447 raise F5ModuleError(str(ex))
448
449 if 'code' in response and response['code'] == 400:
450 if 'message' in response:
451 raise F5ModuleError(response['message'])
452 else:
453 raise F5ModuleError(resp.content)
454
455 def remove_from_device(self):
456 uri = "https://{0}:{1}/mgmt/tm/auth/partition/{2}".format(
457 self.client.provider['server'],
458 self.client.provider['server_port'],
459 self.want.name
460 )
461 resp = self.client.api.delete(uri)
462 if resp.status == 200:
463 return True
464
465
466 class ArgumentSpec(object):
467 def __init__(self):
468 self.supports_check_mode = True
469 argument_spec = dict(
470 name=dict(required=True),
471 description=dict(),
472 route_domain=dict(type='int'),
473 state=dict(
474 choices=['absent', 'present'],
475 default='present'
476 )
477 )
478 self.argument_spec = {}
479 self.argument_spec.update(f5_argument_spec)
480 self.argument_spec.update(argument_spec)
481
482
483 def main():
484 spec = ArgumentSpec()
485
486 module = AnsibleModule(
487 argument_spec=spec.argument_spec,
488 supports_check_mode=spec.supports_check_mode
489 )
490
491 try:
492 mm = ModuleManager(module=module)
493 results = mm.exec_module()
494 module.exit_json(**results)
495 except F5ModuleError as ex:
496 module.fail_json(msg=str(ex))
497
498
499 if __name__ == '__main__':
500 main()