Debian Codegraph @

ansible_collections/f5networks/f5_modules/plugins/modules/bigip_vcmp_guest.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_vcmp_guest
13 short_description: Manages vCMP guests on a BIG-IP
14 description:
15 - Manages vCMP (Virtual Clustered Multiprocessing) guests on a BIG-IP. This functionality
16 only exists on actual hardware and must be enabled by provisioning C(vcmp) with the
17 C(bigip_provision) module.
18 version_added: "1.0.0"
19 options:
20 name:
21 description:
22 - The name of the vCMP guest to manage.
23 type: str
24 required: True
25 vlans:
26 description:
27 - VLANs the guest uses to communicate with other guests, the host, and with
28 the external network. The available VLANs in the list are those that are
29 currently configured on the vCMP host.
30 - The order of these VLANs is not important and is ignored. This module
31 orders the VLANs automatically. Therefore, if you deliberately re-order them
32 in subsequent tasks, this module does B(not) register a change.
33 type: list
34 elements: str
35 initial_image:
36 description:
37 - Specifies the base software release ISO image file for installing the TMOS
38 hypervisor instance and any licensed BIG-IP modules onto the guest's virtual
39 disk. When creating a new guest, this parameter is required. Ensure
40 this image is present on the VCMP host and not only on the VCMP guest. Also, the
41 file reference for this image should be the one present on the host and not on the
42 guest.
43 type: str
44 initial_hotfix:
45 description:
46 - Specifies the hotfix ISO image file which is applied on top of the base
47 image.
48 type: str
49 mgmt_network:
50 description:
51 - Specifies the method by which the management address is used in the vCMP guest.
52 - When C(bridged), specifies the guest can communicate with the vCMP host's
53 management network.
54 - When C(isolated), specifies the guest is isolated from the vCMP host's
55 management network. In this case, the only way a guest can communicate
56 with the vCMP host is through the console port or through a self IP address
57 on the guest that allows traffic through port 22.
58 - When C(host only), prevents the guest from installing images and hotfixes other
59 than those provided by the hypervisor.
60 - If the guest setting is C(isolated) or C(host only), the C(mgmt_address) does
61 not apply.
62 - For mode changing, changing C(bridged) to C(isolated) causes the vCMP
63 host to remove all of the guest's management interfaces from its bridged
64 management network. This immediately disconnects the guest's VMs from the
65 physical management network. Changing C(isolated) to C(bridged) causes the
66 vCMP host to dynamically add the guest's management interfaces to the bridged
67 management network. This immediately connects all of the guest's VMs to the
68 physical management network. Changing this property while the guest is in the
69 C(configured) or C(provisioned) state has no immediate effect.
70 type: str
71 choices:
72 - bridged
73 - isolated
74 - host only
75 delete_virtual_disk:
76 description:
77 - When C(state) is C(absent), the system additionally deletes the virtual disk associated
78 with the vCMP guest. By default, this value is C(false).
79 type: bool
80 default: false
81 mgmt_address:
82 description:
83 - Specifies the IP address and subnet or subnet mask you use to access
84 the guest when you want to manage a module running within the guest. This
85 parameter is required if the C(mgmt_network) parameter is C(bridged).
86 - When creating a new guest, if you do not specify a network or network mask,
87 a default of C(/24) (C(255.255.255.0)) is used.
88 type: str
89 mgmt_route:
90 description:
91 - Specifies the gateway address for the C(mgmt_address).
92 - If this value is not specified when creating a new guest, it is set to C(none).
93 - The value C(none) can be used during an update to remove this value.
94 type: str
95 state:
96 description:
97 - The state of the vCMP guest on the system. Each state implies the actions of
98 all states before it.
99 - When C(configured), guarantees the vCMP guest exists with the provided
100 attributes. Additionally, ensures the vCMP guest is turned off.
101 - When C(disabled), behaves the same way as C(configured), it is just a more
102 user-friendly name.
103 - When C(provisioned), ensures the guest is created and installed.
104 This state does not start the guest; use C(deployed) for that purpose. This state
105 is one step beyond C(present), as C(present) does not install the guest;
106 only sets up the configuration for it to be installed.
107 - When C(present), ensures the guest is properly provisioned and starts
108 the guest so that it is in a running state.
109 - When C(absent), removes the vCMP from the system.
110 type: str
111 choices:
112 - configured
113 - disabled
114 - provisioned
115 - present
116 - absent
117 default: present
118 cores_per_slot:
119 description:
120 - Specifies the number of cores the system allocates to the guest.
121 - Each core represents a portion of CPU and memory. Therefore, the amount of
122 memory allocated per core is directly tied to the amount of CPU. This amount
123 of memory varies per hardware platform type.
124 - The number you can specify depends on the type of hardware you have.
125 - In the event of a reboot, the system persists the guest to the same slot on
126 which it ran prior to the reboot.
127 type: int
128 partition:
129 description:
130 - Device partition to manage resources on.
131 type: str
132 default: Common
133 number_of_slots:
134 description:
135 - Specifies the number of slots for the system to use when creating the guest.
136 - This value dictates how many cores a guest is allocated from each slot to which
137 it is assigned.
138 - Possible values are dependent on the type of blades being used in this cluster.
139 - The default value depends on the type of blades being used in this cluster.
140 type: int
141 min_number_of_slots:
142 description:
143 - Specifies the minimum number of slots the guest must be assigned to in
144 order to deploy.
145 - This field dictates the number of slots to which the guest must be assigned.
146 - At the end of any allocation attempt, if the guest is not assigned to at least
147 this many slots, the attempt fails and the change that initiated it is reverted.
148 - A guest's C(min_number_of_slots) value cannot be greater than its C(number_of_slots).
149 type: int
150 allowed_slots:
151 description:
152 - Contains those slots to which the guest is allowed to be assigned.
153 - When the host determines which slots this guest should be assigned, only slots
154 in this list are considered.
155 - This is a good way to force guests to be assigned only to particular slots, or,
156 by configuring disjoint C(allowed_slots) on two guests, that those guests are
157 never assigned to the same slot.
158 - By default, this list includes every available slot in the cluster. This means
159 the guest may be assigned to any slot by default.
160 type: list
161 elements: str
162 notes:
163 - This module can take a lot of time to deploy vCMP guests. This is an intrinsic
164 limitation of the vCMP system, because it is booting real VMs on the BIG-IP
165 device. This boot time is very similar in length to the time it takes to
166 boot VMs on any other virtualization platform; public or private.
167 - When BIG-IP starts, the VMs are booted sequentially; not in parallel. This
168 means it is not unusual for a vCMP host with many guests to take a
169 long time (60+ minutes) to reboot and bring all the guests online. The
170 BIG-IP chassis will be available before all vCMP guests are online.
171 extends_documentation_fragment: f5networks.f5_modules.f5
172 author:
173 - Tim Rupp (@caphrim007)
174 - Wojciech Wypior (@wojtek0806)
175 '''
176
177 EXAMPLES = r'''
178 - name: Create a vCMP guest
179 bigip_vcmp_guest:
180 name: foo
181 mgmt_network: bridge
182 mgmt_address: 10.20.30.40/24
183 provider:
184 password: secret
185 server: lb.mydomain.com
186 user: admin
187 delegate_to: localhost
188
189 - name: Create a vCMP guest with specific VLANs
190 bigip_vcmp_guest:
191 name: foo
192 mgmt_network: bridge
193 mgmt_address: 10.20.30.40/24
194 vlans:
195 - vlan1
196 - vlan2
197 provider:
198 password: secret
199 server: lb.mydomain.com
200 user: admin
201 delegate_to: localhost
202
203 - name: Remove vCMP guest and disk
204 bigip_vcmp_guest:
205 name: guest1
206 state: absent
207 delete_virtual_disk: true
208 provider:
209 password: secret
210 server: lb.mydomain.com
211 user: admin
212 register: result
213 '''
214
215 RETURN = r'''
216 vlans:
217 description: The VLANs assigned to the vCMP guest, in their full path format.
218 returned: changed
219 type: list
220 sample: ['/Common/vlan1', '/Common/vlan2']
221 '''
222
223 import time
224 from collections import namedtuple
225 from datetime import datetime
226
227 from ansible.module_utils.basic import (
228 AnsibleModule, env_fallback
229 )
230 from ipaddress import ip_interface
231
232 from ..module_utils.bigip import F5RestClient
233 from ..module_utils.common import (
234 F5ModuleError, AnsibleF5Parameters, fq_name, f5_argument_spec
235 )
236 from ..module_utils.ipaddress import is_valid_ip
237 from ..module_utils.urls import parseStats
238 from ..module_utils.icontrol import tmos_version
239 from ..module_utils.teem import send_teem
240
241
242 class Parameters(AnsibleF5Parameters):
243 api_map = {
244 'managementGw': 'mgmt_route',
245 'managementNetwork': 'mgmt_network',
246 'managementIp': 'mgmt_address',
247 'initialImage': 'initial_image',
248 'initialHotfix': 'initial_hotfix',
249 'virtualDisk': 'virtual_disk',
250 'coresPerSlot': 'cores_per_slot',
251 'slots': 'number_of_slots',
252 'minSlots': 'min_number_of_slots',
253 'allowedSlots': 'allowed_slots',
254 }
255
256 api_attributes = [
257 'vlans',
258 'managementNetwork',
259 'managementIp',
260 'initialImage',
261 'initialHotfix',
262 'managementGw',
263 'state',
264 'coresPerSlot',
265 'slots',
266 'minSlots',
267 'allowedSlots',
268 ]
269
270 returnables = [
271 'vlans',
272 'mgmt_network',
273 'mgmt_address',
274 'initial_image',
275 'initial_hotfix',
276 'mgmt_route',
277 'name',
278 'cores_per_slot',
279 'number_of_slots',
280 'min_number_of_slots',
281 'allowed_slots',
282 ]
283
284 updatables = [
285 'vlans',
286 'mgmt_network',
287 'mgmt_address',
288 'initial_image',
289 'initial_hotfix',
290 'mgmt_route',
291 'state',
292 'cores_per_slot',
293 'number_of_slots',
294 'min_number_of_slots',
295 'allowed_slots',
296 ]
297
298
299 class ApiParameters(Parameters):
300 pass
301
302
303 class ModuleParameters(Parameters):
304 @property
305 def mgmt_route(self):
306 if self._values['mgmt_route'] is None:
307 return None
308 elif self._values['mgmt_route'] == 'none':
309 return 'none'
310 if is_valid_ip(self._values['mgmt_route']):
311 return self._values['mgmt_route']
312 else:
313 raise F5ModuleError(
314 "The specified 'mgmt_route' is not a valid IP address."
315 )
316
317 @property
318 def mgmt_address(self):
319 if self._values['mgmt_address'] is None:
320 return None
321 try:
322 addr = ip_interface(u'%s' % str(self._values['mgmt_address']))
323 return str(addr.with_prefixlen)
324 except ValueError:
325 raise F5ModuleError(
326 "The specified 'mgmt_address' is not a valid IP address."
327 )
328
329 @property
330 def mgmt_tuple(self):
331 Destination = namedtuple('Destination', ['ip', 'subnet'])
332 try:
333 parts = self._values['mgmt_address'].split('/')
334 if len(parts) == 2:
335 result = Destination(ip=parts[0], subnet=parts[1])
336 elif len(parts) < 2:
337 result = Destination(ip=parts[0], subnet=None)
338 else:
339 raise F5ModuleError(
340 "The provided mgmt_address is malformed."
341 )
342 except ValueError:
343 result = Destination(ip=None, subnet=None)
344 return result
345
346 @property
347 def state(self):
348 if self._values['state'] == 'present':
349 return 'deployed'
350 elif self._values['state'] in ['configured', 'disabled']:
351 return 'configured'
352 return self._values['state']
353
354 @property
355 def vlans(self):
356 if self._values['vlans'] is None:
357 return None
358 result = [fq_name(self.partition, x) for x in self._values['vlans']]
359 result.sort()
360 return result
361
362 @property
363 def initial_image(self):
364 if self._values['initial_image'] is None:
365 return None
366 if self.initial_image_exists(self._values['initial_image']):
367 return self._values['initial_image']
368 raise F5ModuleError(
369 "The specified 'initial_image' does not exist on the remote device."
370 )
371
372 @property
373 def initial_hotfix(self):
374 if self._values['initial_hotfix'] is None:
375 return None
376 if self.initial_hotfix_exists(self._values['initial_hotfix']):
377 return self._values['initial_hotfix']
378 raise F5ModuleError(
379 "The specified 'initial_hotfix' does not exist on the remote device."
380 )
381
382 def initial_image_exists(self, image):
383 uri = "https://{0}:{1}/mgmt/tm/sys/software/image/".format(
384 self.client.provider['server'],
385 self.client.provider['server_port'],
386 )
387 resp = self.client.api.get(uri)
388 try:
389 response = resp.json()
390 except ValueError:
391 return False
392 if resp.status == 404 or 'code' in response and response['code'] == 404:
393 return False
394 for resource in response['items']:
395 if resource['name'].startswith(image):
396 return True
397 return False
398
399 def initial_hotfix_exists(self, hotfix):
400 uri = "https://{0}:{1}/mgmt/tm/sys/software/hotfix/".format(
401 self.client.provider['server'],
402 self.client.provider['server_port'],
403 )
404 resp = self.client.api.get(uri)
405 try:
406 response = resp.json()
407 except ValueError:
408 return False
409 if resp.status == 404 or 'code' in response and response['code'] == 404:
410 return False
411 for resource in response['items']:
412 if resource['name'].startswith(hotfix):
413 return True
414 return False
415
416 @property
417 def allowed_slots(self):
418 if self._values['allowed_slots'] is None:
419 return None
420 result = self._values['allowed_slots']
421 result.sort()
422 return result
423
424
425 class Changes(Parameters):
426 def to_return(self):
427 result = {}
428 try:
429 for returnable in self.returnables:
430 change = getattr(self, returnable)
431 if isinstance(change, dict):
432 result.update(change)
433 else:
434 result[returnable] = change
435 result = self._filter_params(result)
436 except Exception:
437 pass
438 return result
439
440
441 class UsableChanges(Changes):
442 pass
443
444
445 class ReportableChanges(Changes):
446 pass
447
448
449 class Difference(object):
450 def __init__(self, want, have=None):
451 self.want = want
452 self.have = have
453
454 def compare(self, param):
455 try:
456 result = getattr(self, param)
457 return result
458 except AttributeError:
459 return self.__default(param)
460
461 def __default(self, param):
462 attr1 = getattr(self.want, param)
463 try:
464 attr2 = getattr(self.have, param)
465 if attr1 != attr2:
466 return attr1
467 except AttributeError:
468 return attr1
469
470 @property
471 def mgmt_address(self):
472 want = self.want.mgmt_tuple
473 if want.subnet is None:
474 raise F5ModuleError(
475 "A subnet must be specified when changing the mgmt_address."
476 )
477 if self.want.mgmt_address != self.have.mgmt_address:
478 return self.want.mgmt_address
479
480 @property
481 def allowed_slots(self):
482 if self.want.allowed_slots is None:
483 return None
484 if self.have.allowed_slots is None:
485 return self.want.allowed_slots
486 if set(self.want.allowed_slots) != set(self.have.allowed_slots):
487 return self.want.allowed_slots
488
489
490 class ModuleManager(object):
491 def __init__(self, *args, **kwargs):
492 self.module = kwargs.get('module', None)
493 self.client = F5RestClient(**self.module.params)
494 self.want = ModuleParameters(client=self.client, params=self.module.params)
495 self.have = None
496 self.changes = ReportableChanges()
497
498 def _set_changed_options(self):
499 changed = {}
500 for key in Parameters.returnables:
501 if getattr(self.want, key) is not None:
502 changed[key] = getattr(self.want, key)
503 if changed:
504 self.changes = UsableChanges(params=changed)
505
506 def _update_changed_options(self):
507 diff = Difference(self.want, self.have)
508 updatables = Parameters.updatables
509 changed = dict()
510 for k in updatables:
511 change = diff.compare(k)
512 if change is None:
513 continue
514 else:
515 changed[k] = change
516 if changed:
517 self.changes = UsableChanges(params=changed)
518 return True
519 return False
520
521 def _announce_deprecations(self, result):
522 warnings = result.pop('__warnings', [])
523 for warning in warnings:
524 self.module.deprecate(
525 msg=warning['msg'],
526 version=warning['version']
527 )
528
529 def should_update(self):
530 result = self._update_changed_options()
531 if result:
532 return True
533 return False
534
535 def exec_module(self):
536 start = datetime.now().isoformat()
537 version = tmos_version(self.client)
538 changed = False
539 result = dict()
540 state = self.want.state
541
542 if state in ['configured', 'provisioned', 'deployed']:
543 changed = self.present()
544 elif state == "absent":
545 changed = self.absent()
546
547 reportable = ReportableChanges(params=self.changes.to_return())
548 changes = reportable.to_return()
549 result.update(**changes)
550 result.update(dict(changed=changed))
551 self._announce_deprecations(result)
552 send_teem(start, self.client, self.module, version)
553 return result
554
555 def present(self):
556 if self.exists():
557 return self.update()
558 else:
559 return self.create()
560
561 def absent(self):
562 if self.exists():
563 return self.remove()
564 return False
565
566 def update(self):
567 self.have = self.read_current_from_device()
568 if not self.should_update():
569 return False
570 if self.module.check_mode:
571 return True
572 if self.changes.cores_per_slot:
573 if not self.is_configured():
574 self.configure()
575 self.update_on_device()
576 if self.want.state == 'provisioned':
577 self.provision()
578 elif self.want.state == 'deployed':
579 self.deploy()
580 elif self.want.state == 'configured':
581 self.configure()
582 return True
583
584 def remove(self):
585 if self.module.check_mode:
586 return True
587 if self.want.delete_virtual_disk:
588 self.have = self.read_current_from_device()
589 self.remove_from_device()
590 if self.exists():
591 raise F5ModuleError("Failed to delete the resource.")
592 if self.want.delete_virtual_disk:
593 self.remove_virtual_disk()
594 return True
595
596 def create(self):
597 self._set_changed_options()
598 if self.module.check_mode:
599 return True
600 if self.want.mgmt_tuple.subnet is None:
601 self.want.update(dict(
602 mgmt_address='{0}/255.255.255.0'.format(self.want.mgmt_tuple.ip)
603 ))
604 self.create_on_device()
605 if self.want.state == 'provisioned':
606 self.provision()
607 elif self.want.state == 'deployed':
608 self.deploy()
609 elif self.want.state == 'configured':
610 self.configure()
611 return True
612
613 def exists(self):
614 uri = "https://{0}:{1}/mgmt/tm/vcmp/guest/{2}".format(
615 self.client.provider['server'],
616 self.client.provider['server_port'],
617 self.want.name
618 )
619 resp = self.client.api.get(uri)
620 try:
621 response = resp.json()
622 except ValueError as ex:
623 raise F5ModuleError(str(ex))
624
625 if resp.status == 404 or 'code' in response and response['code'] == 404:
626 return False
627 if resp.status in [200, 201] or 'code' in response and response['code'] in [200, 201]:
628 return True
629
630 errors = [401, 403, 409, 500, 501, 502, 503, 504]
631
632 if resp.status in errors or 'code' in response and response['code'] in errors:
633 if 'message' in response:
634 raise F5ModuleError(response['message'])
635 else:
636 raise F5ModuleError(resp.content)
637
638 def create_on_device(self):
639 params = self.changes.api_params()
640 params['name'] = self.want.name
641 uri = "https://{0}:{1}/mgmt/tm/vcmp/guest/".format(
642 self.client.provider['server'],
643 self.client.provider['server_port'],
644 )
645 resp = self.client.api.post(uri, json=params)
646 try:
647 response = resp.json()
648 except ValueError as ex:
649 raise F5ModuleError(str(ex))
650
651 if 'code' in response and response['code'] in [400, 403]:
652 if 'message' in response:
653 raise F5ModuleError(response['message'])
654 else:
655 raise F5ModuleError(resp.content)
656 return response['selfLink']
657
658 def update_on_device(self):
659 params = self.changes.api_params()
660 uri = "https://{0}:{1}/mgmt/tm/vcmp/guest/{2}".format(
661 self.client.provider['server'],
662 self.client.provider['server_port'],
663 self.want.name
664 )
665 resp = self.client.api.patch(uri, json=params)
666 try:
667 response = resp.json()
668 except ValueError as ex:
669 raise F5ModuleError(str(ex))
670
671 if 'code' in response and response['code'] == 400:
672 if 'message' in response:
673 raise F5ModuleError(response['message'])
674 else:
675 raise F5ModuleError(resp.content)
676
677 def remove_from_device(self):
678 uri = "https://{0}:{1}/mgmt/tm/vcmp/guest/{2}".format(
679 self.client.provider['server'],
680 self.client.provider['server_port'],
681 self.want.name
682 )
683 response = self.client.api.delete(uri)
684 if response.status == 200:
685 return True
686 raise F5ModuleError(response.content)
687
688 def read_current_from_device(self):
689 uri = "https://{0}:{1}/mgmt/tm/vcmp/guest/{2}".format(
690 self.client.provider['server'],
691 self.client.provider['server_port'],
692 self.want.name
693 )
694 resp = self.client.api.get(uri)
695 try:
696 response = resp.json()
697 except ValueError as ex:
698 raise F5ModuleError(str(ex))
699
700 if 'code' in response and response['code'] == 400:
701 if 'message' in response:
702 raise F5ModuleError(response['message'])
703 else:
704 raise F5ModuleError(resp.content)
705 return ApiParameters(params=response)
706
707 def remove_virtual_disk(self):
708 if self.virtual_disk_exists():
709 return self.remove_virtual_disk_from_device()
710 return False
711
712 def get_virtual_disks_on_device(self):
713 uri = "https://{0}:{1}/mgmt/tm/vcmp/virtual-disk/".format(
714 self.client.provider['server'],
715 self.client.provider['server_port'],
716 )
717 resp = self.client.api.get(uri)
718 try:
719 response = resp.json()
720 except ValueError as ex:
721 raise F5ModuleError(str(ex))
722
723 if 'code' in response and response['code'] == 400:
724 if 'message' in response:
725 raise F5ModuleError(response['message'])
726 else:
727 raise F5ModuleError(resp.content)
728
729 if 'items' in response:
730 return response
731
732 def virtual_disk_exists(self):
733 """Checks if a virtual disk exists for a guest
734
735 The virtual disk names can differ based on the device vCMP is installed on.
736 For instance, on a shuttle-series device with no slots, you will see disks
737 that resemble the following
738
739 guest1.img
740
741 On an 8-blade Viprion with slots though, you will see
742
743 guest1.img/1
744
745 The "/1" in this case is the slot that it is a part of. This method looks
746 for the virtual-disk without the trailing slot.
747
748 Returns:
749 dict
750 """
751 response = self.get_virtual_disks_on_device()
752 check = '{0}'.format(self.have.virtual_disk)
753 for resource in response['items']:
754 if resource['name'].startswith(check):
755 return True
756 else:
757 return False
758
759 def remove_virtual_disk_from_device(self):
760 check = '{0}'.format(self.have.virtual_disk)
761 response = self.get_virtual_disks_on_device()
762 for resource in response['items']:
763 if resource['name'].startswith(check):
764 uri = "https://{0}:{1}/mgmt/tm/vcmp/virtual-disk/{2}".format(
765 self.client.provider['server'],
766 self.client.provider['server_port'],
767 resource['name'].replace('/', '~')
768 )
769 response = self.client.api.delete(uri)
770
771 if response.status == 200:
772 continue
773 else:
774 raise F5ModuleError(response.content)
775
776 return True
777
778 def is_configured(self):
779 """Checks to see if guest is disabled
780
781 A disabled guest is fully disabled once their Stats go offline.
782 Until that point they are still in the process of disabling.
783
784 :return:
785 """
786 uri = "https://{0}:{1}/mgmt/tm/vcmp/guest/{2}/stats".format(
787 self.client.provider['server'],
788 self.client.provider['server_port'],
789 self.want.name
790 )
791 resp = self.client.api.get(uri)
792
793 try:
794 response = resp.json()
795 except ValueError as ex:
796 raise F5ModuleError(str(ex))
797
798 if resp.status == 404 or 'code' in response and response['code'] == 404:
799 return True
800
801 if 'code' in response and response['code'] == 400:
802 if 'message' in response:
803 raise F5ModuleError(response['message'])
804 else:
805 raise F5ModuleError(resp.content)
806
807 return False
808
809 def is_provisioned(self):
810 uri = "https://{0}:{1}/mgmt/tm/vcmp/guest/{2}/stats".format(
811 self.client.provider['server'],
812 self.client.provider['server_port'],
813 self.want.name
814 )
815 resp = self.client.api.get(uri)
816
817 try:
818 response = resp.json()
819 except ValueError:
820 return False
821 if 'code' in response and response['code'] == 400:
822 if 'message' in response:
823 raise F5ModuleError(response['message'])
824 else:
825 raise F5ModuleError(resp.content)
826
827 if resp.status == 404 or 'code' in response and response['code'] == 404:
828 return False
829
830 result = parseStats(response)
831
832 if 'stats' in result:
833 if result['stats']['requestedState'] == 'provisioned':
834 if result['stats']['vmStatus'] == 'stopped':
835 return True
836 return False
837
838 def is_deployed(self):
839 uri = "https://{0}:{1}/mgmt/tm/vcmp/guest/{2}/stats".format(
840 self.client.provider['server'],
841 self.client.provider['server_port'],
842 self.want.name
843 )
844 resp = self.client.api.get(uri)
845
846 try:
847 response = resp.json()
848 except ValueError:
849 return False
850 if 'code' in response and response['code'] == 400:
851 if 'message' in response:
852 raise F5ModuleError(response['message'])
853 else:
854 raise F5ModuleError(resp.content)
855
856 if resp.status == 404 or 'code' in response and response['code'] == 404:
857 return False
858
859 result = parseStats(response)
860
861 if 'stats' in result:
862 if result['stats']['requestedState'] == 'deployed':
863 if result['stats']['vmStatus'] == 'running':
864 return True
865 return False
866
867 def configure(self):
868 if self.is_configured():
869 return False
870 self.configure_on_device()
871 self.wait_for_configured()
872 return True
873
874 def configure_on_device(self):
875 params = dict(state='configured')
876 uri = "https://{0}:{1}/mgmt/tm/vcmp/guest/{2}".format(
877 self.client.provider['server'],
878 self.client.provider['server_port'],
879 self.want.name
880 )
881 resp = self.client.api.patch(uri, json=params)
882 try:
883 response = resp.json()
884 except ValueError as ex:
885 raise F5ModuleError(str(ex))
886
887 if 'code' in response and response['code'] == 400:
888 if 'message' in response:
889 raise F5ModuleError(response['message'])
890 else:
891 raise F5ModuleError(resp.content)
892
893 def wait_for_configured(self):
894 nops = 0
895 while nops < 3:
896 if self.is_configured():
897 nops += 1
898 time.sleep(1)
899
900 def provision(self):
901 if self.is_provisioned():
902 return False
903 self.provision_on_device()
904 self.wait_for_provisioned()
905
906 def provision_on_device(self):
907 params = dict(state='provisioned')
908 uri = "https://{0}:{1}/mgmt/tm/vcmp/guest/{2}".format(
909 self.client.provider['server'],
910 self.client.provider['server_port'],
911 self.want.name
912 )
913 resp = self.client.api.patch(uri, json=params)
914 try:
915 response = resp.json()
916 except ValueError as ex:
917 raise F5ModuleError(str(ex))
918
919 if 'code' in response and response['code'] == 400:
920 if 'message' in response:
921 raise F5ModuleError(response['message'])
922 else:
923 raise F5ModuleError(resp.content)
924
925 def wait_for_provisioned(self):
926 nops = 0
927 while nops < 3:
928 if self.is_provisioned():
929 nops += 1
930 time.sleep(1)
931
932 def deploy(self):
933 if self.is_deployed():
934 return False
935 self.deploy_on_device()
936 self.wait_for_deployed()
937
938 def deploy_on_device(self):
939 params = dict(state='deployed')
940 uri = "https://{0}:{1}/mgmt/tm/vcmp/guest/{2}".format(
941 self.client.provider['server'],
942 self.client.provider['server_port'],
943 self.want.name
944 )
945 resp = self.client.api.patch(uri, json=params)
946 try:
947 response = resp.json()
948 except ValueError as ex:
949 raise F5ModuleError(str(ex))
950
951 if 'code' in response and response['code'] == 400:
952 if 'message' in response:
953 raise F5ModuleError(response['message'])
954 else:
955 raise F5ModuleError(resp.content)
956
957 def wait_for_deployed(self):
958 nops = 0
959 while nops < 3:
960 if self.is_deployed():
961 nops += 1
962 time.sleep(1)
963
964
965 class ArgumentSpec(object):
966 def __init__(self):
967 self.supports_check_mode = True
968 argument_spec = dict(
969 name=dict(required=True),
970 vlans=dict(
971 type='list',
972 elements='str',
973 ),
974 mgmt_network=dict(choices=['bridged', 'isolated', 'host only']),
975 mgmt_address=dict(),
976 mgmt_route=dict(),
977 initial_image=dict(),
978 initial_hotfix=dict(),
979 state=dict(
980 default='present',
981 choices=['configured', 'disabled', 'provisioned', 'absent', 'present']
982 ),
983 delete_virtual_disk=dict(
984 type='bool',
985 default='no'
986 ),
987 cores_per_slot=dict(type='int'),
988 number_of_slots=dict(type='int'),
989 min_number_of_slots=dict(type='int'),
990 allowed_slots=dict(
991 type='list',
992 elements='str',
993 ),
994 partition=dict(
995 default='Common',
996 fallback=(env_fallback, ['F5_PARTITION'])
997 )
998 )
999 self.argument_spec = {}
1000 self.argument_spec.update(f5_argument_spec)
1001 self.argument_spec.update(argument_spec)
1002 self.required_if = [
1003 ['mgmt_network', 'bridged', ['mgmt_address']]
1004 ]
1005
1006
1007 def main():
1008 spec = ArgumentSpec()
1009
1010 module = AnsibleModule(
1011 argument_spec=spec.argument_spec,
1012 supports_check_mode=spec.supports_check_mode,
1013 required_if=spec.required_if
1014 )
1015
1016 try:
1017 mm = ModuleManager(module=module)
1018 results = mm.exec_module()
1019 module.exit_json(**results)
1020 except F5ModuleError as ex:
1021 module.fail_json(msg=str(ex))
1022
1023
1024 if __name__ == '__main__':
1025 main()