Debian Codegraph @

ansible_collections/community/libvirt/plugins/modules/virt.py

raw
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3
4 # Copyright: (c) 2007, 2012 Red Hat, Inc
5 # Michael DeHaan <[email protected]>
6 # Seth Vidal <[email protected]>
7 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
8
9 from __future__ import absolute_import, division, print_function
10 __metaclass__ = type
11
12
13 DOCUMENTATION = '''
14 ---
15 module: virt
16 short_description: Manages virtual machines supported by libvirt
17 description:
18 - Manages virtual machines supported by I(libvirt).
19 options:
20 flags:
21 choices: [ 'managed_save', 'snapshots_metadata', 'nvram', 'keep_nvram', 'checkpoints_metadata', 'delete_volumes']
22 description:
23 - Pass additional parameters.
24 - Currently only implemented with command C(undefine).
25 Specify which metadata should be removed with C(undefine).
26 Useful option to be able to C(undefine) guests with UEFI nvram.
27 C(nvram) and C(keep_nvram) are conflicting and mutually exclusive.
28 Consider option C(force) if all related metadata should be removed.
29 type: list
30 elements: str
31 force:
32 description:
33 - Enforce an action.
34 - Currently only implemented with command C(undefine).
35 This option can be used instead of providing all C(flags).
36 If C(true), C(undefine) removes also any related nvram or other metadata, if existing.
37 If C(false) or not set, C(undefine) executes only if there is no nvram or other metadata existing.
38 Otherwise the task fails and the guest is kept defined without change.
39 C(true) and option C(flags) should not be provided together. In this case
40 C(undefine) ignores C(true), considers only C(flags) and issues a warning.
41 type: bool
42 extends_documentation_fragment:
43 - community.libvirt.virt.options_uri
44 - community.libvirt.virt.options_xml
45 - community.libvirt.virt.options_guest
46 - community.libvirt.virt.options_autostart
47 - community.libvirt.virt.options_state
48 - community.libvirt.virt.options_command
49 - community.libvirt.virt.options_mutate_flags
50 - community.libvirt.requirements
51 attributes:
52 check_mode:
53 description: Supports check_mode.
54 support: full
55 author:
56 - Ansible Core Team
57 - Michael DeHaan
58 - Seth Vidal (@skvidal)
59 '''
60
61 EXAMPLES = '''
62 # a playbook task line:
63 - name: Start a VM
64 community.libvirt.virt:
65 name: alpha
66 state: running
67
68 # /usr/bin/ansible invocations
69 # ansible host -m virt -a "name=alpha command=status"
70 # ansible host -m virt -a "name=alpha command=get_xml"
71 # ansible host -m virt -a "name=alpha command=create uri=lxc:///"
72
73 # defining and launching an LXC guest
74 - name: Define a VM
75 community.libvirt.virt:
76 command: define
77 xml: "{{ lookup('template', 'container-template.xml.j2') }}"
78 uri: 'lxc:///'
79 - name: start vm
80 community.libvirt.virt:
81 name: foo
82 state: running
83 uri: 'lxc:///'
84
85 # setting autostart on a qemu VM (default uri)
86 - name: Set autostart for a VM
87 community.libvirt.virt:
88 name: foo
89 autostart: true
90
91 # Defining a VM and making is autostart with host. VM will be off after this task
92 - name: Define vm from xml and set autostart
93 community.libvirt.virt:
94 command: define
95 xml: "{{ lookup('template', 'vm_template.xml.j2') }}"
96 autostart: true
97
98 # Undefine VM only, if it has no existing nvram or other metadata
99 - name: Undefine qemu VM
100 community.libvirt.virt:
101 command: undefine
102 name: foo
103
104 # Undefine VM and force remove all of its related metadata (nvram, snapshots, etc.)
105 - name: "Undefine qemu VM with force"
106 community.libvirt.virt:
107 command: undefine
108 name: foo
109 force: true
110
111 # Undefine VM and remove all of its specified metadata specified
112 # Result would the same as with force=true
113 - name: Undefine qemu VM with list of flags
114 community.libvirt.virt:
115 command: undefine
116 name: foo
117 flags: managed_save, snapshots_metadata, nvram, checkpoints_metadata
118
119 # Undefine VM, but keep its nvram
120 - name: Undefine qemu VM and keep its nvram
121 community.libvirt.virt:
122 command: undefine
123 name: foo
124 flags: keep_nvram
125
126 # Listing VMs
127 - name: List all VMs
128 community.libvirt.virt:
129 command: list_vms
130 register: all_vms
131
132 - name: List only running VMs
133 community.libvirt.virt:
134 command: list_vms
135 state: running
136 register: running_vms
137 '''
138
139 RETURN = '''
140 # for list_vms command
141 list_vms:
142 description: The list of vms defined on the remote system.
143 type: list
144 returned: success
145 sample: [
146 "build.example.org",
147 "dev.example.org"
148 ]
149 # for status command
150 status:
151 description: The status of the VM, among running, crashed, paused and shutdown.
152 type: str
153 sample: "success"
154 returned: success
155 '''
156
157 import traceback
158
159 from ansible_collections.community.libvirt.plugins.module_utils.libvirt import (
160 VIRT_STATE_NAME_MAP, VMNotFound, LibvirtConnection, VIRT_SUCCESS
161 )
162
163 try:
164 import libvirt
165 from libvirt import libvirtError
166 except ImportError:
167 HAS_VIRT = False
168 else:
169 HAS_VIRT = True
170
171 try:
172 from lxml import etree
173 except ImportError:
174 HAS_XML = False
175 else:
176 HAS_XML = True
177
178 from ansible.module_utils.basic import AnsibleModule
179 from ansible.module_utils._text import to_native
180
181 ALL_COMMANDS = []
182 VM_COMMANDS = ['create', 'define', 'destroy', 'get_xml', 'get_interfaces', 'pause', 'shutdown', 'status', 'start', 'stop', 'undefine', 'unpause', 'uuid']
183 HOST_COMMANDS = ['freemem', 'info', 'list_vms', 'nodeinfo', 'virttype']
184 ALL_COMMANDS.extend(VM_COMMANDS)
185 ALL_COMMANDS.extend(HOST_COMMANDS)
186
187 ENTRY_UNDEFINE_FLAGS_MAP = {
188 'managed_save': 1,
189 'snapshots_metadata': 2,
190 'nvram': 4,
191 'keep_nvram': 8,
192 'checkpoints_metadata': 16,
193 'delete_volumes': 32,
194 }
195
196 MUTATE_FLAGS = ['ADD_UUID', 'ADD_MAC_ADDRESSES', 'ADD_MAC_ADDRESSES_FUZZY']
197
198 ALL_FLAGS = []
199 ALL_FLAGS.extend(ENTRY_UNDEFINE_FLAGS_MAP.keys())
200
201
202 class Virt(object):
203
204 def __init__(self, uri, module):
205 self.module = module
206 self.uri = uri
207
208 def __get_conn(self):
209 self.conn = LibvirtConnection(self.uri, self.module)
210 return self.conn
211
212 def get_vm(self, vmid):
213 self.__get_conn()
214 return self.conn.find_vm(vmid)
215
216 def state(self):
217 vms = self.list_vms()
218 state = []
219 for vm in vms:
220 state_blurb = self.conn.get_status(vm)
221 state.append("%s %s" % (vm, state_blurb))
222 return state
223
224 def info(self):
225 vms = self.list_vms()
226 info = dict()
227 for vm in vms:
228 data = self.conn.find_vm(vm).info()
229 # libvirt returns maxMem, memory, and cpuTime as long()'s, which
230 # xmlrpclib tries to convert to regular int's during serialization.
231 # This throws exceptions, so convert them to strings here and
232 # assume the other end of the xmlrpc connection can figure things
233 # out or doesn't care.
234 info[vm] = dict(
235 state=VIRT_STATE_NAME_MAP.get(data[0], "unknown"),
236 maxMem=str(data[1]),
237 memory=str(data[2]),
238 nrVirtCpu=data[3],
239 cpuTime=str(data[4]),
240 autostart=self.conn.get_autostart(vm),
241 )
242
243 return info
244
245 def nodeinfo(self):
246 self.__get_conn()
247 data = self.conn.nodeinfo()
248 info = dict(
249 cpumodel=str(data[0]),
250 phymemory=str(data[1]),
251 cpus=str(data[2]),
252 cpumhz=str(data[3]),
253 numanodes=str(data[4]),
254 sockets=str(data[5]),
255 cpucores=str(data[6]),
256 cputhreads=str(data[7])
257 )
258 return info
259
260 def list_vms(self, state=None):
261 self.conn = self.__get_conn()
262 vms = self.conn.find_vm(-1)
263 results = []
264 for x in vms:
265 try:
266 if state:
267 vmstate = self.conn.get_status2(x)
268 if vmstate == state:
269 results.append(x.name())
270 else:
271 results.append(x.name())
272 except Exception:
273 pass
274 return results
275
276 def virttype(self):
277 return self.__get_conn().get_type()
278
279 def autostart(self, vmid, as_flag):
280 self.conn = self.__get_conn()
281 if self.module.check_mode:
282 return self.conn.get_autostart(vmid) != as_flag
283
284 # Change autostart flag only if needed
285 if self.conn.get_autostart(vmid) != as_flag:
286 self.conn.set_autostart(vmid, as_flag)
287 return True
288
289 return False
290
291 def freemem(self):
292 self.conn = self.__get_conn()
293 return self.conn.getFreeMemory()
294
295 def shutdown(self, vmid):
296 """ Make the machine with the given vmid stop running. Whatever that takes. """
297 if self.module.check_mode:
298 return 0
299 self.__get_conn()
300 self.conn.shutdown(vmid)
301 return 0
302
303 def pause(self, vmid):
304 """ Pause the machine with the given vmid. """
305 if self.module.check_mode:
306 return 0
307 self.__get_conn()
308 return self.conn.suspend(vmid)
309
310 def unpause(self, vmid):
311 """ Unpause the machine with the given vmid. """
312 if self.module.check_mode:
313 return 0
314 self.__get_conn()
315 return self.conn.resume(vmid)
316
317 def create(self, vmid):
318 """ Start the machine via the given vmid """
319 if self.module.check_mode:
320 return 0
321 self.__get_conn()
322 return self.conn.create(vmid)
323
324 def start(self, vmid):
325 """ Start the machine via the given id/name """
326 if self.module.check_mode:
327 return 0
328 self.__get_conn()
329 return self.conn.create(vmid)
330
331 def destroy(self, vmid):
332 """ Pull the virtual power from the virtual domain, giving it virtually no time to virtually shut down. """
333 if self.module.check_mode:
334 return 0
335 self.__get_conn()
336 return self.conn.destroy(vmid)
337
338 def undefine(self, vmid, flag):
339 """ Stop a domain, and then wipe it from the face of the earth. (delete disk/config file) """
340 if self.module.check_mode:
341 return {
342 'changed': vmid in self.list_vms(),
343 'command': 0,
344 }
345 self.__get_conn()
346 res = self.conn.undefine(vmid, flag)
347 return {
348 'changed': res == 0,
349 'command': res,
350 }
351
352 def status(self, vmid):
353 """
354 Return a state suitable for server consumption. Aka, codes.py values, not XM output.
355 """
356 self.__get_conn()
357 return self.conn.get_status(vmid)
358
359 def get_xml(self, vmid):
360 """
361 Receive a Vm id as input
362 Return an xml describing vm config returned by a libvirt call
363 """
364
365 self.__get_conn()
366 return self.conn.get_xml(vmid)
367
368 def get_maxVcpus(self, vmid):
369 """
370 Gets the max number of VCPUs on a guest
371 """
372
373 self.__get_conn()
374 return self.conn.get_maxVcpus(vmid)
375
376 def get_max_memory(self, vmid):
377 """
378 Gets the max memory on a guest
379 """
380
381 self.__get_conn()
382 return self.conn.get_MaxMemory(vmid)
383
384 def define(self, xml):
385 """
386 Define a guest with the given xml
387 """
388 if self.module.check_mode:
389 return 0
390 self.__get_conn()
391 return self.conn.define_from_xml(xml)
392
393 def get_uuid(self, vmid):
394 self.__get_conn()
395 return self.conn.get_uuid(vmid)
396
397 def get_interfaces(self, vmid):
398 """
399 Get Interface Name and Mac Address from xml
400 """
401 self.__get_conn()
402 return self.conn.get_interfaces(vmid)
403
404 def delete_domain_volumes(self, vmid):
405 self.__get_conn()
406 return self.conn.delete_domain_volumes(vmid)
407
408
409 # A dict of interface types (found in their `type` attribute) to the
410 # corresponding "source" attribute name of their <source> elements
411 # user networks don't have a <source> element
412 #
413 # We do not support fuzzy matching against any interface types
414 # not defined here
415 INTERFACE_SOURCE_ATTRS = {
416 'network': 'network',
417 'bridge': 'bridge',
418 'direct': 'dev',
419 'user': None,
420 }
421
422
423 def handle_define(module, v):
424 ''' handle `command: define` '''
425 xml = module.params.get('xml', None)
426 guest = module.params.get('name', None)
427 autostart = module.params.get('autostart', None)
428 mutate_flags = module.params.get('mutate_flags', [])
429 parser = etree.XMLParser(remove_blank_text=True)
430
431 if not xml:
432 module.fail_json(msg="define requires 'xml' argument")
433 try:
434 incoming_xml = etree.fromstring(xml, parser)
435 except etree.XMLSyntaxError:
436 # TODO: provide info from parser
437 module.fail_json(msg="given XML is invalid")
438
439 # We'll support supplying the domain's name either from 'name' parameter or xml
440 #
441 # But we will fail if both are defined and not equal.
442 domain_name = incoming_xml.findtext("./name")
443 if domain_name is not None:
444 if guest is not None and domain_name != guest:
445 module.fail_json("given 'name' parameter does not match name in XML")
446 else:
447 if guest is None:
448 module.fail_json("missing 'name' parameter and no name provided in XML")
449 domain_name = guest
450 # since there's no <name> in the xml, we'll add it
451 etree.SubElement(incoming_xml, 'name').text = domain_name
452
453 if domain_name == '':
454 module.fail_json(msg="domain name cannot be an empty string")
455
456 res = dict()
457
458 # From libvirt docs (https://libvirt.org/html/libvirt-libvirt-domain.html#virDomainDefineXML):
459 # -- A previous definition for this domain with the same UUID and name would
460 # be overridden if it already exists.
461 #
462 # If a domain is defined without a <uuid>, libvirt will generate one for it.
463 # If an attempt is made to re-define the same xml (with the same <name> and
464 # no <uuid>), libvirt will complain with the following error:
465 #
466 # operation failed: domain '<name>' already exists with <uuid>
467 #
468 # If a domain with a similiar <name> but different <uuid> is defined,
469 # libvirt complains with the same error. However, if a domain is defined
470 # with the same <name> and <uuid> as an existing domain, then libvirt will
471 # update the domain with the new definition (automatically handling
472 # addition/removal of devices. some changes may require a boot).
473 try:
474 existing_domain = v.get_vm(domain_name)
475 existing_xml_raw = existing_domain.XMLDesc(libvirt.VIR_DOMAIN_XML_INACTIVE)
476 existing_xml = etree.fromstring(existing_xml_raw, parser)
477 except VMNotFound:
478 existing_domain = None
479 existing_xml_raw = None
480 existing_xml = None
481
482 if existing_domain is not None:
483 # we are updating a domain's definition
484
485 incoming_uuid = incoming_xml.findtext('./uuid')
486 existing_uuid = existing_domain.UUIDString()
487
488 if incoming_uuid is not None and incoming_uuid != existing_uuid:
489 # A user should not try defining a domain with the same name but
490 # different UUID
491 module.fail_json(msg="attempting to re-define domain %s/%s with a different UUID: %s" % (
492 domain_name, existing_uuid, incoming_uuid
493 ))
494 else:
495 if 'ADD_UUID' in mutate_flags and incoming_uuid is None:
496 # Users will often want to define their domains without an explicit
497 # UUID, instead giving them a unique name - so we support bringing
498 # over the UUID from the existing domain
499 etree.SubElement(incoming_xml, 'uuid').text = existing_uuid
500
501 existing_devices = existing_xml.find('./devices')
502
503 if 'ADD_MAC_ADDRESSES' in mutate_flags:
504 for interface in incoming_xml.xpath('./devices/interface[not(mac) and alias]'):
505 search_alias = interface.find('alias').get('name')
506 xpath = "./interface[alias[@name='%s']]" % search_alias
507 try:
508 matched_interface = existing_devices.xpath(xpath)[0]
509 existing_devices.remove(matched_interface)
510 etree.SubElement(interface, 'mac', {
511 'address': matched_interface.find('mac').get('address')
512 })
513 except IndexError:
514 module.warn("Could not match interface %i of incoming XML by alias %s." % (
515 interface.getparent().index(interface) + 1, search_alias
516 ))
517
518 if 'ADD_MAC_ADDRESSES_FUZZY' in mutate_flags:
519 # the counts of interfaces of a similar type/source
520 # key'd with tuple of (type, source)
521 similar_interface_counts = {}
522
523 def get_interface_count(_type, source=None):
524 key = (_type, source if _type != "user" else None)
525 if key not in similar_interface_counts:
526 similar_interface_counts[key] = 1
527 else:
528 similar_interface_counts[key] += 1
529 return similar_interface_counts[key]
530
531 # iterate user-defined interfaces
532 for interface in incoming_xml.xpath('./devices/interface'):
533 _type = interface.get('type')
534
535 if interface.find('mac') is not None and interface.find('alias') is not None:
536 continue
537
538 if _type not in INTERFACE_SOURCE_ATTRS:
539 module.warn("Skipping fuzzy MAC matching for interface %i of incoming XML: unsupported interface type '%s'." % (
540 interface.getparent().index(interface) + 1, _type
541 ))
542 continue
543
544 source_attr = INTERFACE_SOURCE_ATTRS[_type]
545 source = interface.find('source').get(source_attr) if source_attr else None
546 similar_count = get_interface_count(_type, source)
547
548 if interface.find('mac') is not None:
549 # we want to count these, but not try to change their MAC address
550 continue
551
552 if source:
553 xpath = "./interface[@type='%s' and source[@%s='%s']]" % (
554 _type, source_attr, source)
555 else:
556 xpath = "./interface[@type = '%s']" % source_attr
557
558 matching_interfaces = existing_devices.xpath(xpath)
559 try:
560 matched_interface = matching_interfaces[similar_count - 1]
561 etree.SubElement(interface, 'mac', {
562 'address': matched_interface.find('./mac').get('address'),
563 })
564 except IndexError:
565 module.warn("Could not fuzzy match interface %i of incoming XML." % (
566 interface.getparent().index(interface) + 1
567 ))
568
569 try:
570 domain_xml = etree.tostring(incoming_xml, pretty_print=True).decode()
571
572 if module.check_mode:
573 before = etree.tostring(existing_xml, pretty_print=True).decode() if existing_xml else ''
574 res.update({
575 'changed': before != domain_xml,
576 'diff': {
577 'before': before,
578 'after': domain_xml
579 },
580 })
581 return res
582
583 domain = v.define(domain_xml)
584
585 if existing_domain is not None:
586 # In this case, we may have updated the definition or it might be the same.
587 # We compare the domain's previous xml with its new state and diff
588 # the changes. This allows users to fix their xml if it results in
589 # non-idempotent behaviour (e.g. libvirt mutates it each time)
590 new_xml = domain.XMLDesc(libvirt.VIR_DOMAIN_XML_INACTIVE)
591 if existing_xml_raw != new_xml:
592 res.update({
593 'changed': True,
594 'change_reason': 'domain definition changed',
595 'diff': {
596 'before': existing_xml_raw,
597 'after': new_xml
598 }
599 })
600 else:
601 # there was no existing XML, so this is a newly created domain
602 res.update({'changed': True, 'created': domain.name()})
603
604 except libvirtError as e:
605 module.fail_json(msg='libvirtError: %s' % e.get_error_message())
606 except Exception as e:
607 module.fail_json(msg='an unknown error occured: %s' % e)
608
609 if autostart is not None and v.autostart(domain_name, autostart):
610 res.update({'changed': True, 'change_reason': 'autostart'})
611
612 return res
613
614
615 def core(module):
616
617 state = module.params.get('state', None)
618 autostart = module.params.get('autostart', None)
619 guest = module.params.get('name', None)
620 command = module.params.get('command', None)
621 force = module.params.get('force', None)
622 flags = module.params.get('flags', None)
623 uri = module.params.get('uri', None)
624
625 v = Virt(uri, module)
626 res = dict()
627
628 if state and command == 'list_vms':
629 res = v.list_vms(state=state)
630 if not isinstance(res, dict):
631 res = {command: res}
632 return VIRT_SUCCESS, res
633
634 if autostart is not None and command != 'define':
635 if not guest:
636 module.fail_json(msg="autostart requires 1 argument: name")
637 try:
638 v.get_vm(guest)
639 except VMNotFound:
640 module.fail_json(msg="domain %s not found" % guest)
641 res['changed'] = v.autostart(guest, autostart)
642 if not command and not state:
643 return VIRT_SUCCESS, res
644
645 if state:
646 if not guest:
647 module.fail_json(msg="state change requires a guest specified")
648
649 if state == 'running':
650 if v.status(guest) == 'paused':
651 res['changed'] = True
652 res['msg'] = v.unpause(guest)
653 elif v.status(guest) != 'running':
654 res['changed'] = True
655 res['msg'] = v.start(guest)
656 elif state == 'shutdown':
657 if v.status(guest) != 'shutdown':
658 res['changed'] = True
659 res['msg'] = v.shutdown(guest)
660 elif state == 'destroyed':
661 if v.status(guest) != 'shutdown':
662 res['changed'] = True
663 res['msg'] = v.destroy(guest)
664 elif state == 'paused':
665 if v.status(guest) == 'running':
666 res['changed'] = True
667 res['msg'] = v.pause(guest)
668 else:
669 module.fail_json(msg="unexpected state")
670
671 return VIRT_SUCCESS, res
672
673 if command:
674 def exec_virt(*args):
675 res = getattr(v, command)(*args)
676 if not isinstance(res, dict):
677 res = {command: res}
678 return res
679
680 if command in VM_COMMANDS:
681 if command == 'define':
682 res.update(handle_define(module, v))
683
684 elif not guest:
685 module.fail_json(msg="%s requires 1 argument: guest" % command)
686
687 elif command == 'undefine':
688 # Use the undefine function with flag to also handle various metadata.
689 # This is especially important for UEFI enabled guests with nvram.
690 # Provide flag as an integer of all desired bits, see 'ENTRY_UNDEFINE_FLAGS_MAP'.
691 # Integer 55 takes care of all cases (55 = 1 + 2 + 4 + 16 + 32). flag = 0
692 flag = 0
693 if flags is not None:
694 if force is True:
695 module.warn("Ignoring 'force', because 'flags' are provided.")
696 nv = ['nvram', 'keep_nvram']
697 # Check mutually exclusive flags
698 if set(nv) <= set(flags):
699 raise ValueError("Flags '%s' are mutually exclusive" % "' and '".join(nv))
700 for item in flags:
701 # Get and add flag integer from mapping, otherwise 0.
702 flag += ENTRY_UNDEFINE_FLAGS_MAP.get(item, 0)
703 elif force is True:
704 flag = 55
705 # Finally, execute with flag
706 res = exec_virt(guest, flag)
707
708 elif command == 'uuid':
709 res = {'uuid': v.get_uuid(guest)}
710
711 else:
712 res = exec_virt(guest)
713
714 return VIRT_SUCCESS, res
715
716 elif hasattr(v, command):
717 res = exec_virt()
718 return VIRT_SUCCESS, res
719
720 else:
721 module.fail_json(msg="Command %s not recognized" % command)
722
723 module.fail_json(msg="expected state or command parameter to be specified")
724
725
726 def main():
727 module = AnsibleModule(
728 argument_spec=dict(
729 name=dict(type='str', aliases=['guest']),
730 state=dict(type='str', choices=['destroyed', 'paused', 'running', 'shutdown']),
731 autostart=dict(type='bool'),
732 command=dict(type='str', choices=ALL_COMMANDS),
733 flags=dict(type='list', elements='str', choices=ALL_FLAGS),
734 force=dict(type='bool'),
735 uri=dict(type='str', default='qemu:///system'),
736 xml=dict(type='str'),
737 mutate_flags=dict(type='list', elements='str', choices=MUTATE_FLAGS, default=['ADD_UUID']),
738 ),
739 supports_check_mode=True
740 )
741
742 if not HAS_VIRT:
743 module.fail_json(
744 msg='The `libvirt` module is not importable. Check the requirements.'
745 )
746
747 if not HAS_XML:
748 module.fail_json(
749 msg='The `lxml` module is not importable. Check the requirements.'
750 )
751
752 rc = VIRT_SUCCESS
753 try:
754 rc, result = core(module)
755 except Exception as e:
756 module.fail_json(msg=to_native(e), exception=traceback.format_exc())
757
758 if rc != 0: # something went wrong emit the msg
759 module.fail_json(rc=rc, msg=result)
760 else:
761 module.exit_json(**result)
762
763
764 if __name__ == '__main__':
765 main()