Debian Codegraph @

ansible_collections/f5networks/f5_modules/plugins/modules/bigiq_regkey_license.py

raw symbols SCIP
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3 #
4 # Copyright: (c) 2022, 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: bigiq_regkey_license
13 short_description: Manages licenses in a BIG-IQ registration key pool
14 description:
15 - Manages licenses in a BIG-IQ registration key pool.
16 version_added: "1.0.0"
17 options:
18 regkey_pool:
19 description:
20 - The registration key pool in which you want to place the license.
21 - You must give your registration pools unique names. While
22 BIG-IQ does not require this, this module does. If you do not,
23 the behavior of the module is undefined and you may end up putting
24 licenses in the wrong registration key pool.
25 type: str
26 required: True
27 license_key:
28 description:
29 - The license key to put in the pool.
30 type: str
31 required: True
32 addon_keys:
33 description:
34 - The addon keys to put in the pool.
35 type: list
36 elements: str
37 version_added: "1.16.0"
38 description:
39 description:
40 - Description of the license.
41 type: str
42 accept_eula:
43 description:
44 - A key that signifies you accept the F5 EULA for this license.
45 - A copy of the EULA can be found here https://askf5.f5.com/csp/article/K12902
46 - This is required when C(state) is C(present).
47 type: bool
48 state:
49 description:
50 - The state of the regkey license in the pool on the system.
51 - When C(present), guarantees the license exists in the pool.
52 - When C(absent), removes the license from the pool.
53 type: str
54 choices:
55 - absent
56 - present
57 default: present
58 requirements:
59 - BIG-IQ >= 5.3.0
60 extends_documentation_fragment: f5networks.f5_modules.f5
61 author:
62 - Tim Rupp (@caphrim007)
63 - Wojciech Wypior(@wojtek0806)
64 '''
65
66 EXAMPLES = r'''
67 - name: Add a registration key license to a pool
68 bigiq_regkey_license:
69 regkey_pool: foo-pool
70 license_key: XXXXX-XXXXX-XXXXX-XXXXX-XXXXX
71 accept_eula: true
72 provider:
73 password: secret
74 server: cm.mydomain.com
75 user: admin
76 delegate_to: localhost
77
78 - name: Add a registration key license with addon keys to a pool
79 bigiq_regkey_license:
80 regkey_pool: foo-pool
81 license_key: XXXXX-XXXXX-XXXXX-XXXXX-XXXXX
82 addon_keys:
83 - YYYY-YYY-YYY
84 - ZZZZ-ZZZ-ZZZ
85 accept_eula: true
86 provider:
87 password: secret
88 server: cm.mydomain.com
89 user: admin
90 delegate_to: localhost
91
92 - name: Remove a registration key license from a pool
93 bigiq_regkey_license:
94 regkey_pool: foo-pool
95 license_key: XXXXX-XXXXX-XXXXX-XXXXX-XXXXX
96 state: absent
97 provider:
98 password: secret
99 server: cm.mydomain.com
100 user: admin
101 delegate_to: localhost
102 '''
103
104 RETURN = r'''
105 description:
106 description: The new description of the license key.
107 returned: changed
108 type: str
109 sample: My license for BIG-IP 1
110 '''
111
112 import time
113 from datetime import datetime
114
115 from ansible.module_utils.basic import AnsibleModule
116
117 from ..module_utils.bigip import F5RestClient
118 from ..module_utils.common import (
119 F5ModuleError, AnsibleF5Parameters, f5_argument_spec
120 )
121 from ..module_utils.icontrol import bigiq_version
122 from ..module_utils.teem import send_teem
123
124
125 class Parameters(AnsibleF5Parameters):
126 api_map = {
127 'regKey': 'license_key',
128 'addOnKeys': 'addon_keys'
129 }
130
131 api_attributes = [
132 'regKey', 'description', 'addOnKeys'
133 ]
134
135 returnables = [
136 'description'
137 ]
138
139 updatables = [
140 'description'
141 ]
142
143 def to_return(self):
144 result = {}
145 try:
146 for returnable in self.returnables:
147 result[returnable] = getattr(self, returnable)
148 result = self._filter_params(result)
149 except Exception:
150 raise
151 return result
152
153
154 class ApiParameters(Parameters):
155 pass
156
157
158 class ModuleParameters(Parameters):
159 @property
160 def regkey_pool_uuid(self):
161 if self._values['regkey_pool_uuid']:
162 return self._values['regkey_pool_uuid']
163 collection = self.read_current_from_device()
164 resource = next((x for x in collection if x.name == self.regkey_pool), None)
165 if resource is None:
166 raise F5ModuleError("Could not find the specified regkey pool.")
167 self._values['regkey_pool_uuid'] = resource.id
168 return resource.id
169
170 def read_current_from_device(self):
171 uri = "https://{0}:{1}/mgmt/cm/device/licensing/pool/regkey/licenses".format(
172 self.client.provider['server'],
173 self.client.provider['server_port'],
174 )
175 resp = self.client.api.get(uri)
176 try:
177 response = resp.json()
178 except ValueError as ex:
179 raise F5ModuleError(str(ex))
180
181 if 'code' in response and response['code'] == 400:
182 if 'message' in response:
183 raise F5ModuleError(response['message'])
184 else:
185 raise F5ModuleError(resp.content)
186 if 'items' not in response:
187 return []
188 result = [ApiParameters(params=r) for r in response['items']]
189 return result
190
191
192 class Changes(Parameters):
193 def to_return(self):
194 result = {}
195 try:
196 for returnable in self.returnables:
197 result[returnable] = getattr(self, returnable)
198 result = self._filter_params(result)
199 except Exception:
200 raise
201 return result
202
203
204 class UsableChanges(Changes):
205 pass
206
207
208 class ReportableChanges(Changes):
209 pass
210
211
212 class Difference(object):
213 def __init__(self, want, have=None):
214 self.want = want
215 self.have = have
216
217 def compare(self, param):
218 try:
219 result = getattr(self, param)
220 return result
221 except AttributeError:
222 return self.__default(param)
223
224 def __default(self, param):
225 attr1 = getattr(self.want, param)
226 try:
227 attr2 = getattr(self.have, param)
228 if attr1 != attr2:
229 return attr1
230 except AttributeError:
231 return attr1
232
233
234 class ModuleManager(object):
235 def __init__(self, *args, **kwargs):
236 self.module = kwargs.get('module', None)
237 self.client = F5RestClient(**self.module.params)
238 self.want = ModuleParameters(client=self.client, params=self.module.params)
239 self.have = ApiParameters()
240 self.changes = UsableChanges()
241
242 def _set_changed_options(self):
243 changed = {}
244 for key in Parameters.returnables:
245 if getattr(self.want, key) is not None:
246 changed[key] = getattr(self.want, key)
247 if changed:
248 self.changes = UsableChanges(params=changed)
249
250 def _update_changed_options(self):
251 diff = Difference(self.want, self.have)
252 updatables = Parameters.updatables
253 changed = dict()
254 for k in updatables:
255 change = diff.compare(k)
256 if change is None:
257 continue
258 else:
259 if isinstance(change, dict):
260 changed.update(change)
261 else:
262 changed[k] = change
263 if changed:
264 self.changes = UsableChanges(params=changed)
265 return True
266 return False
267
268 def should_update(self):
269 result = self._update_changed_options()
270 if result:
271 return True
272 return False
273
274 def exec_module(self):
275 start = datetime.now().isoformat()
276 version = bigiq_version(self.client)
277 changed = False
278 result = dict()
279 state = self.want.state
280
281 if state == "present":
282 changed = self.present()
283 elif state == "absent":
284 changed = self.absent()
285
286 reportable = ReportableChanges(params=self.changes.to_return())
287 changes = reportable.to_return()
288 result.update(**changes)
289 result.update(dict(changed=changed))
290 self._announce_deprecations(result)
291 send_teem(start, self.client, self.module, version)
292 return result
293
294 def _announce_deprecations(self, result):
295 warnings = result.pop('__warnings', [])
296 for warning in warnings:
297 self.module.deprecate(
298 msg=warning['msg'],
299 version=warning['version']
300 )
301
302 def present(self):
303 if self.exists():
304 return self.update()
305 else:
306 return self.create()
307
308 def exists(self):
309 uri = "https://{0}:{1}/mgmt/cm/device/licensing/pool/regkey/licenses/{2}/offerings/{3}".format(
310 self.client.provider['server'],
311 self.client.provider['server_port'],
312 self.want.regkey_pool_uuid,
313 self.want.license_key
314 )
315 resp = self.client.api.get(uri)
316 try:
317 response = resp.json()
318 except ValueError:
319 return False
320 if resp.status == 404 or 'code' in response and response['code'] == 404:
321 return False
322 return True
323
324 def update(self):
325 self.have = self.read_current_from_device()
326 if not self.should_update():
327 return False
328 if self.module.check_mode:
329 return True
330 self.update_on_device()
331 return True
332
333 def remove(self):
334 if self.module.check_mode:
335 return True
336 self.remove_from_device()
337 if self.exists():
338 raise F5ModuleError("Failed to delete the resource.")
339 return True
340
341 def create(self):
342 self._set_changed_options()
343 if self.module.check_mode:
344 return True
345 if self.want.accept_eula is False:
346 raise F5ModuleError(
347 "To add a license, you must accept its EULA. Please see the module documentation for a link to this."
348 )
349 self.create_on_device()
350 return True
351
352 def create_on_device(self):
353 params = self.want.api_params()
354 params['name'] = self.want.name
355 params['status'] = 'ACTIVATING_AUTOMATIC'
356 uri = "https://{0}:{1}/mgmt/cm/device/licensing/pool/regkey/licenses/{2}/offerings".format(
357 self.client.provider['server'],
358 self.client.provider['server_port'],
359 self.want.regkey_pool_uuid,
360 )
361 resp = self.client.api.post(uri, json=params)
362 try:
363 response = resp.json()
364 except ValueError as ex:
365 raise F5ModuleError(str(ex))
366
367 if 'code' in response and response['code'] in [400, 403]:
368 if 'message' in response:
369 raise F5ModuleError(response['message'])
370 else:
371 raise F5ModuleError(resp.content)
372
373 for x in range(60):
374 resource = self.read_current_from_device()
375 if resource.status == 'READY':
376 break
377 elif resource.status == 'ACTIVATING_AUTOMATIC_NEED_EULA_ACCEPT':
378 params = dict(
379 status='ACTIVATING_AUTOMATIC_EULA_ACCEPTED',
380 eulaText=resource.eulaText
381 )
382 uri = "https://{0}:{1}/mgmt/cm/device/licensing/pool/regkey/licenses/{2}/offerings/{3}".format(
383 self.client.provider['server'],
384 self.client.provider['server_port'],
385 self.want.regkey_pool_uuid,
386 self.want.license_key
387 )
388 resp = self.client.api.patch(uri, json=params)
389 try:
390 response = resp.json()
391 except ValueError as ex:
392 raise F5ModuleError(str(ex))
393
394 if 'code' in response and response['code'] == 400:
395 if 'message' in response:
396 raise F5ModuleError(response['message'])
397 else:
398 raise F5ModuleError(resp.content)
399 elif resource.status == 'ACTIVATION_FAILED':
400 raise F5ModuleError(str(resource.message))
401 time.sleep(1)
402
403 def update_on_device(self):
404 params = self.changes.api_params()
405 uri = "https://{0}:{1}/mgmt/cm/device/licensing/pool/regkey/licenses/{2}/offerings/{3}".format(
406 self.client.provider['server'],
407 self.client.provider['server_port'],
408 self.want.regkey_pool_uuid,
409 self.want.license_key
410 )
411 resp = self.client.api.patch(uri, json=params)
412 try:
413 response = resp.json()
414 except ValueError as ex:
415 raise F5ModuleError(str(ex))
416
417 if 'code' in response and response['code'] == 400:
418 if 'message' in response:
419 raise F5ModuleError(response['message'])
420 else:
421 raise F5ModuleError(resp.content)
422
423 def absent(self):
424 if self.exists():
425 return self.remove()
426 return False
427
428 def remove_from_device(self):
429 uri = "https://{0}:{1}/mgmt/cm/device/licensing/pool/regkey/licenses/{2}/offerings/{3}".format(
430 self.client.provider['server'],
431 self.client.provider['server_port'],
432 self.want.regkey_pool_uuid,
433 self.want.license_key
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/cm/device/licensing/pool/regkey/licenses/{2}/offerings/{3}".format(
441 self.client.provider['server'],
442 self.client.provider['server_port'],
443 self.want.regkey_pool_uuid,
444 self.want.license_key
445 )
446 resp = self.client.api.get(uri)
447 try:
448 response = resp.json()
449 except ValueError as ex:
450 raise F5ModuleError(str(ex))
451
452 if 'code' in response and response['code'] == 400:
453 if 'message' in response:
454 raise F5ModuleError(response['message'])
455 else:
456 raise F5ModuleError(resp.content)
457 return ApiParameters(params=response)
458
459
460 class ArgumentSpec(object):
461 def __init__(self):
462 self.supports_check_mode = True
463 argument_spec = dict(
464 regkey_pool=dict(required=True, no_log=True),
465 license_key=dict(required=True, no_log=True),
466 addon_keys=dict(type='list', elements='str', no_log=True),
467 description=dict(),
468 accept_eula=dict(type='bool'),
469 state=dict(
470 default='present',
471 choices=['present', 'absent']
472 ),
473 )
474 self.argument_spec = {}
475 self.argument_spec.update(f5_argument_spec)
476 self.argument_spec.update(argument_spec)
477 self.required_if = [
478 ['state', 'present', ['accept_eula']]
479 ]
480
481
482 def main():
483 spec = ArgumentSpec()
484
485 module = AnsibleModule(
486 argument_spec=spec.argument_spec,
487 supports_check_mode=spec.supports_check_mode,
488 required_if=spec.required_if,
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()