Debian Codegraph @

ansible_collections/f5networks/f5_modules/plugins/modules/bigiq_utility_license_assignment.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: bigiq_utility_license_assignment
13 short_description: Manage utility license assignment on BIG-IPs from a BIG-IQ
14 description:
15 - Manages the assignment of utility licenses on a BIG-IQ. Assignment means
16 the license is assigned to a BIG-IP, or it needs to be assigned to a BIG-IP.
17 Additionally, this module supports revoking the assignments from BIG-IP devices.
18 version_added: "1.0.0"
19 options:
20 unit_of_measure:
21 description:
22 - Sets the rate at which this license usage is billed.
23 - Depending on your license, you may have different units of measure
24 available to you. If a particular unit is not available to you, the module
25 notifies you at licensing time.
26 type: str
27 choices:
28 - hourly
29 - daily
30 - monthly
31 - yearly
32 default: hourly
33 key:
34 description:
35 - The registration key from which you want choose an offering.
36 type: str
37 required: True
38 offering:
39 description:
40 - Name of the license offering to assign to the device.
41 type: str
42 required: True
43 device:
44 description:
45 - When C(managed) is C(false), specifies the address, or hostname, where the BIG-IQ
46 can reach the remote device to register.
47 - When C(managed) is C(true), specifies the managed device, or device UUID,
48 you want to register.
49 - If C(managed) is C(true), it is very important you do not have more than
50 one device with the same name. BIG-IQ internally recognizes devices by their ID,
51 and therefore, this module cannot guarantee the correct device will be
52 registered. The device returned is the device that is used.
53 type: str
54 required: True
55 managed:
56 description:
57 - Whether the specified device is a managed or un-managed device.
58 - When C(state) is C(present), this parameter is required.
59 type: bool
60 device_port:
61 description:
62 - Specifies the port of the remote device to connect to.
63 - If this parameter is not specified, the default is C(443).
64 type: int
65 default: 443
66 device_username:
67 description:
68 - The username used to connect to the remote device.
69 - This username should be one that has sufficient privileges on the remote device
70 to do licensing. Usually this is the C(Administrator) role.
71 - When C(managed) is C(false), this parameter is required.
72 type: str
73 device_password:
74 description:
75 - The password of the C(device_username).
76 - When C(managed) is C(false), this parameter is required.
77 type: str
78 state:
79 description:
80 - When C(present), ensures the device is assigned the specified license.
81 - When C(absent), ensures the license is revokes from the remote device and freed
82 on the BIG-IQ.
83 type: str
84 choices:
85 - present
86 - absent
87 default: present
88 extends_documentation_fragment: f5networks.f5_modules.f5
89 author:
90 - Tim Rupp (@caphrim007)
91 '''
92
93 EXAMPLES = r'''
94 - name: Register an unmanaged device
95 bigiq_utility_license_assignment:
96 key: XXXX-XXXX-XXXX-XXXX-XXXX
97 offering: F5-BIG-MSP-AFM-10G-LIC
98 device: 1.1.1.1
99 managed: false
100 device_username: admin
101 device_password: secret
102 state: present
103 provider:
104 password: secret
105 server: cm.mydomain.com
106 user: admin
107 delegate_to: localhost
108
109 - name: Register a managed device, by name
110 bigiq_utility_license_assignment:
111 key: XXXX-XXXX-XXXX-XXXX-XXXX
112 offering: F5-BIG-MSP-AFM-10G-LIC
113 device: bigi1.foo.com
114 managed: true
115 state: present
116 provider:
117 password: secret
118 server: cm.mydomain.com
119 user: admin
120 delegate_to: localhost
121
122 - name: Register a managed device, by UUID
123 bigiq_utility_license_assignment:
124 key: XXXX-XXXX-XXXX-XXXX-XXXX
125 offering: F5-BIG-MSP-AFM-10G-LIC
126 device: 7141a063-7cf8-423f-9829-9d40599fa3e0
127 managed: true
128 state: present
129 provider:
130 password: secret
131 server: cm.mydomain.com
132 user: admin
133 delegate_to: localhost
134 '''
135
136 RETURN = r'''
137 # only common fields returned
138 '''
139
140 import re
141 from datetime import datetime
142
143 from ansible.module_utils.basic import AnsibleModule
144
145 from ..module_utils.bigip import F5RestClient
146 from ..module_utils.common import (
147 F5ModuleError, AnsibleF5Parameters, f5_argument_spec
148 )
149 from ..module_utils.icontrol import bigiq_version
150 from ..module_utils.ipaddress import is_valid_ip
151 from ..module_utils.teem import send_teem
152
153
154 class Parameters(AnsibleF5Parameters):
155 api_map = {
156 'deviceReference': 'device_reference',
157 'deviceAddress': 'device_address',
158 'httpsPort': 'device_port',
159 'unitOfMeasure': 'unit_of_measure'
160 }
161
162 api_attributes = [
163 'deviceReference', 'deviceAddress', 'httpsPort', 'managed', 'unitOfMeasure'
164 ]
165
166 returnables = [
167 'device_address', 'device_reference', 'device_username', 'device_password',
168 'device_port', 'managed', 'unit_of_measure'
169 ]
170
171 updatables = [
172 'device_reference', 'device_address', 'device_username', 'device_password',
173 'device_port', 'managed', 'unit_of_measure'
174 ]
175
176 def to_return(self):
177 result = {}
178 try:
179 for returnable in self.returnables:
180 result[returnable] = getattr(self, returnable)
181 result = self._filter_params(result)
182 except Exception:
183 pass
184 return result
185
186
187 class ApiParameters(Parameters):
188 pass
189
190
191 class ModuleParameters(Parameters):
192 @property
193 def device_password(self):
194 if self._values['device_password'] is None:
195 return None
196 return self._values['device_password']
197
198 @property
199 def device_username(self):
200 if self._values['device_username'] is None:
201 return None
202 return self._values['device_username']
203
204 @property
205 def device_address(self):
206 if self.device_is_address:
207 return self._values['device']
208
209 @property
210 def device_port(self):
211 if self._values['device_port'] is None:
212 return None
213 return int(self._values['device_port'])
214
215 @property
216 def device_is_address(self):
217 if is_valid_ip(self.device):
218 return True
219 return False
220
221 @property
222 def device_is_id(self):
223 pattern = r'[A-Za-z0-9]{8}-[A-Za-z0-9]{4}-[A-Za-z0-9]{4}-[A-Za-z0-9]{4}-[A-Za-z0-9]{12}'
224 if re.match(pattern, self.device):
225 return True
226 return False
227
228 @property
229 def device_is_name(self):
230 if not self.device_is_address and not self.device_is_id:
231 return True
232 return False
233
234 @property
235 def device_reference(self):
236 if not self.managed:
237 return None
238 if self.device_is_address:
239 # This range lookup is how you do lookups for single IP addresses. Weird.
240 filter = "address+eq+'{0}...{0}'".format(self.device)
241 elif self.device_is_name:
242 filter = "hostname+eq+'{0}'".format(self.device)
243 elif self.device_is_id:
244 filter = "uuid+eq+'{0}'".format(self.device)
245 else:
246 raise F5ModuleError(
247 "Unknown device format '{0}'".format(self.device)
248 )
249
250 uri = "https://{0}:{1}/mgmt/shared/resolver/device-groups/cm-bigip-allBigIpDevices/devices/" \
251 "?$filter={2}&$top=1".format(self.client.provider['server'],
252 self.client.provider['server_port'], filter)
253 resp = self.client.api.get(uri)
254 try:
255 response = resp.json()
256 except ValueError as ex:
257 raise F5ModuleError(str(ex))
258 if resp.status == 200 and response['totalItems'] == 0:
259 raise F5ModuleError(
260 "No device with the specified address was found."
261 )
262 elif 'code' in response and response['code'] == 400:
263 if 'message' in response:
264 raise F5ModuleError(response['message'])
265 else:
266 raise F5ModuleError(resp._content)
267 id = response['items'][0]['uuid']
268 result = dict(
269 link='https://localhost/mgmt/shared/resolver/device-groups/cm-bigip-allBigIpDevices/devices/{0}'.format(id)
270 )
271 return result
272
273 @property
274 def offering_id(self):
275 filter = "(name+eq+'{0}')".format(self.offering)
276 uri = 'https://{0}:{1}/mgmt/cm/device/licensing/pool/utility/licenses/{2}/offerings?$filter={3}&$top=1'.format(
277 self.client.provider['server'],
278 self.client.provider['server_port'],
279 self.key,
280 filter
281 )
282 resp = self.client.api.get(uri)
283 try:
284 response = resp.json()
285 except ValueError as ex:
286 raise F5ModuleError(str(ex))
287 if resp.status == 200 and response['totalItems'] == 0:
288 raise F5ModuleError(
289 "No offering with the specified name was found."
290 )
291 elif 'code' in response and response['code'] == 400:
292 if 'message' in response:
293 raise F5ModuleError(response['message'])
294 else:
295 raise F5ModuleError(resp._content)
296 return response['items'][0]['id']
297
298 @property
299 def member_id(self):
300 if self.device_is_address:
301 # This range lookup is how you do lookups for single IP addresses. Weird.
302 filter = "deviceAddress+eq+'{0}...{0}'".format(self.device)
303 elif self.device_is_name:
304 filter = "deviceName+eq+'{0}'".format(self.device)
305 elif self.device_is_id:
306 filter = "deviceMachineId+eq+'{0}'".format(self.device)
307 else:
308 raise F5ModuleError(
309 "Unknown device format '{0}'".format(self.device)
310 )
311 uri = 'https://{0}:{1}/mgmt/cm/device/licensing/pool/utility/licenses/{2}/offerings/{3}/members/?$filter={4}'.format(
312 self.client.provider['server'],
313 self.client.provider['server_port'],
314 self.key,
315 self.offering_id,
316 filter
317 )
318 resp = self.client.api.get(uri)
319 try:
320 response = resp.json()
321 except ValueError as ex:
322 raise F5ModuleError(str(ex))
323
324 if resp.status == 200 and response['totalItems'] == 0:
325 return None
326 elif 'code' in response and response['code'] == 400:
327 if 'message' in response:
328 raise F5ModuleError(response['message'])
329 else:
330 raise F5ModuleError(resp._content)
331 result = response['items'][0]['id']
332 return result
333
334
335 class Changes(Parameters):
336 pass
337
338
339 class UsableChanges(Changes):
340 @property
341 def device_port(self):
342 if self._values['managed']:
343 return None
344 return self._values['device_port']
345
346 @property
347 def device_username(self):
348 if self._values['managed']:
349 return None
350 return self._values['device_username']
351
352 @property
353 def device_password(self):
354 if self._values['managed']:
355 return None
356 return self._values['device_password']
357
358 @property
359 def device_reference(self):
360 if not self._values['managed']:
361 return None
362 return self._values['device_reference']
363
364 @property
365 def device_address(self):
366 if self._values['managed']:
367 return None
368 return self._values['device_address']
369
370 @property
371 def managed(self):
372 return None
373
374
375 class ReportableChanges(Changes):
376 pass
377
378
379 class Difference(object):
380 def __init__(self, want, have=None):
381 self.want = want
382 self.have = have
383
384 def compare(self, param):
385 try:
386 result = getattr(self, param)
387 return result
388 except AttributeError:
389 return self.__default(param)
390
391 def __default(self, param):
392 attr1 = getattr(self.want, param)
393 try:
394 attr2 = getattr(self.have, param)
395 if attr1 != attr2:
396 return attr1
397 except AttributeError:
398 return attr1
399
400
401 class ModuleManager(object):
402 def __init__(self, *args, **kwargs):
403 self.module = kwargs.get('module', None)
404 self.client = F5RestClient(**self.module.params)
405 self.want = ModuleParameters(params=self.module.params, client=self.client)
406 self.have = ApiParameters()
407 self.changes = UsableChanges()
408
409 def _set_changed_options(self):
410 changed = {}
411 for key in Parameters.returnables:
412 if getattr(self.want, key) is not None:
413 changed[key] = getattr(self.want, key)
414 if changed:
415 self.changes = Changes(params=changed)
416
417 def _update_changed_options(self):
418 diff = Difference(self.want, self.have)
419 updatables = Parameters.updatables
420 changed = dict()
421 for k in updatables:
422 change = diff.compare(k)
423 if change is None:
424 continue
425 else:
426 if isinstance(change, dict):
427 changed.update(change)
428 else:
429 changed[k] = change
430 if changed:
431 self.changes = Changes(params=changed)
432 return True
433 return False
434
435 def should_update(self):
436 result = self._update_changed_options()
437 if result:
438 return True
439 return False
440
441 def exec_module(self):
442 start = datetime.now().isoformat()
443 version = bigiq_version(self.client)
444 changed = False
445 result = dict()
446 state = self.want.state
447
448 if state == "present":
449 changed = self.present()
450 elif state == "absent":
451 changed = self.absent()
452
453 reportable = ReportableChanges(params=self.changes.to_return())
454 changes = reportable.to_return()
455 result.update(**changes)
456 result.update(dict(changed=changed))
457 self._announce_deprecations(result)
458 send_teem(start, self.client, self.module, version)
459 return result
460
461 def _announce_deprecations(self, result):
462 warnings = result.pop('__warnings', [])
463 for warning in warnings:
464 self.module.deprecate(
465 msg=warning['msg'],
466 version=warning['version']
467 )
468
469 def present(self):
470 if self.exists():
471 return False
472 return self.create()
473
474 def exists(self):
475 if self.want.member_id is None:
476 return False
477 uri = 'https://{0}:{1}/mgmt/cm/device/licensing/pool/utility/licenses/{2}/offerings/{3}/members/{4}'.format(
478 self.client.provider['server'],
479 self.client.provider['server_port'],
480 self.want.key,
481 self.want.offering_id,
482 self.want.member_id
483 )
484 resp = self.client.api.get(uri)
485 if resp.status == 200:
486 return True
487 return False
488
489 def remove(self):
490 self._set_changed_options()
491 if self.module.check_mode:
492 return True
493 self.remove_from_device()
494 if self.exists():
495 raise F5ModuleError("Failed to delete the resource.")
496 return True
497
498 def create(self):
499 self._set_changed_options()
500 if not self.want.managed:
501 if self.want.device_username is None:
502 raise F5ModuleError(
503 "You must specify a 'device_username' when working with unmanaged devices."
504 )
505 if self.want.device_password is None:
506 raise F5ModuleError(
507 "You must specify a 'device_password' when working with unmanaged devices."
508 )
509 if self.module.check_mode:
510 return True
511 self.create_on_device()
512 if not self.exists():
513 raise F5ModuleError(
514 "Failed to license the remote device."
515 )
516 self.wait_for_device_to_be_licensed()
517 return True
518
519 def create_on_device(self):
520 params = self.changes.api_params()
521 uri = 'https://{0}:{1}/mgmt/cm/device/licensing/pool/utility/licenses/{2}/offerings/{3}/members/'.format(
522 self.client.provider['server'],
523 self.client.provider['server_port'],
524 self.want.key,
525 self.want.offering_id,
526 )
527
528 if not self.want.managed:
529 params['username'] = self.want.device_username
530 params['password'] = self.want.device_password
531
532 resp = self.client.api.post(uri, json=params)
533 try:
534 response = resp.json()
535 except ValueError as ex:
536 raise F5ModuleError(str(ex))
537
538 if 'code' in response and response['code'] == 400:
539 if 'message' in response:
540 raise F5ModuleError(response['message'])
541 else:
542 raise F5ModuleError(resp.content)
543
544 def wait_for_device_to_be_licensed(self):
545 count = 0
546 uri = 'https://{0}:{1}/mgmt/cm/device/licensing/pool/utility/licenses/{2}/offerings/{3}/members/{4}'.format(
547 self.client.provider['server'],
548 self.client.provider['server_port'],
549 self.want.key,
550 self.want.offering_id,
551 self.want.member_id,
552 )
553 while count < 3:
554 resp = self.client.api.get(uri)
555 try:
556 response = resp.json()
557 except ValueError as ex:
558 raise F5ModuleError(str(ex))
559
560 if 'code' in response and response['code'] == 400:
561 if 'message' in response:
562 raise F5ModuleError(response['message'])
563 else:
564 raise F5ModuleError(resp.content)
565 if response['status'] == 'LICENSED':
566 count += 1
567 else:
568 count = 0
569
570 def absent(self):
571 if self.exists():
572 return self.remove()
573 return False
574
575 def remove_from_device(self):
576 uri = 'https://{0}:{1}/mgmt/cm/device/licensing/pool/utility/licenses/{2}/offerings/{3}/members/{4}'.format(
577 self.client.provider['server'],
578 self.client.provider['server_port'],
579 self.want.key,
580 self.want.offering_id,
581 self.want.member_id
582 )
583 params = {}
584 if not self.want.managed:
585 params.update(self.changes.api_params())
586 params['id'] = self.want.member_id
587 params['username'] = self.want.device_username
588 params['password'] = self.want.device_password
589 self.client.api.delete(uri, json=params)
590
591
592 class ArgumentSpec(object):
593 def __init__(self):
594 self.supports_check_mode = True
595 argument_spec = dict(
596 offering=dict(required=True),
597 unit_of_measure=dict(
598 default='hourly',
599 choices=[
600 'hourly', 'daily', 'monthly', 'yearly'
601 ]
602 ),
603 key=dict(required=True, no_log=True),
604 device=dict(required=True),
605 managed=dict(type='bool'),
606 device_port=dict(type='int', default=443),
607 device_username=dict(no_log=True),
608 device_password=dict(no_log=True),
609 state=dict(default='present', choices=['absent', 'present'])
610 )
611 self.argument_spec = {}
612 self.argument_spec.update(f5_argument_spec)
613 self.argument_spec.update(argument_spec)
614 self.required_if = [
615 ['state', 'present', ['key', 'managed']],
616 ['managed', False, ['device', 'device_username', 'device_password']],
617 ['managed', True, ['device']]
618 ]
619
620
621 def main():
622 spec = ArgumentSpec()
623
624 module = AnsibleModule(
625 argument_spec=spec.argument_spec,
626 supports_check_mode=spec.supports_check_mode,
627 required_if=spec.required_if
628 )
629
630 try:
631 mm = ModuleManager(module=module)
632 results = mm.exec_module()
633 module.exit_json(**results)
634 except F5ModuleError as ex:
635 module.fail_json(msg=str(ex))
636
637
638 if __name__ == '__main__':
639 main()