Debian Codegraph @

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