Debian Codegraph @

ansible_collections/community/vmware/plugins/modules/vmware_guest_snapshot.py

raw
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3
4 # Copyright: (c) 2018, Ansible Project
5 # This module is also sponsored by E.T.A.I. (www.etai.fr)
6 # GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
7 # SPDX-License-Identifier: GPL-3.0-or-later
8
9 from __future__ import absolute_import, division, print_function
10 __metaclass__ = type
11
12
13 DOCUMENTATION = r'''
14 ---
15 module: vmware_guest_snapshot
16 deprecated:
17 removed_in: 8.0.0
18 why: This module has been L(moved to vmware.vmware,https://github.com/ansible-collections/vmware.vmware/pull/126)
19 alternative: Use M(vmware.vmware.vm_snapshot) instead.
20 short_description: Manages virtual machines snapshots in vCenter
21 description:
22 - This module can be used to create, delete and update snapshot(s) of the given virtual machine.
23 author:
24 - Loic Blot (@nerzhul) <[email protected]>
25 options:
26 state:
27 description:
28 - Manage snapshot(s) attached to a specific virtual machine.
29 - If set to V(present) and snapshot absent, then will create a new snapshot with the given name.
30 - If set to V(present) and snapshot present, then no changes are made.
31 - If set to V(absent) and snapshot present, then snapshot with the given name is removed.
32 - If set to V(absent) and snapshot absent, then no changes are made.
33 - If set to V(revert) and snapshot present, then virtual machine state is reverted to the given snapshot.
34 - If set to V(revert) and snapshot absent, then no changes are made.
35 - If set to V(remove_all) and snapshot(s) present, then all snapshot(s) will be removed.
36 - If set to V(remove_all) and snapshot(s) absent, then no changes are made.
37 choices: ['present', 'absent', 'revert', 'remove_all']
38 default: 'present'
39 type: str
40 name:
41 description:
42 - Name of the virtual machine to work with.
43 - This is required parameter, if O(uuid) or O(moid) is not supplied.
44 type: str
45 name_match:
46 description:
47 - If multiple VMs matching the name, use the first or last found.
48 default: 'first'
49 choices: ['first', 'last']
50 type: str
51 uuid:
52 description:
53 - UUID of the instance to manage if known, this is VMware's BIOS UUID by default.
54 - This is required if O(name) or O(moid) parameter is not supplied.
55 type: str
56 moid:
57 description:
58 - Managed Object ID of the instance to manage if known, this is a unique identifier only within a single vCenter instance.
59 - This is required if O(name) or O(uuid) is not supplied.
60 type: str
61 use_instance_uuid:
62 description:
63 - Whether to use the VMware instance UUID rather than the BIOS UUID.
64 default: false
65 type: bool
66 folder:
67 description:
68 - Destination folder, absolute or relative path to find an existing guest.
69 - This is required parameter, if O(name) is supplied.
70 - The folder should include the datacenter. ESX's datacenter is ha-datacenter.
71 - 'Examples:'
72 - ' folder: /ha-datacenter/vm'
73 - ' folder: ha-datacenter/vm'
74 - ' folder: /datacenter1/vm'
75 - ' folder: datacenter1/vm'
76 - ' folder: /datacenter1/vm/folder1'
77 - ' folder: datacenter1/vm/folder1'
78 - ' folder: /folder1/datacenter1/vm'
79 - ' folder: folder1/datacenter1/vm'
80 - ' folder: /folder1/datacenter1/vm/folder2'
81 type: str
82 datacenter:
83 description:
84 - Destination datacenter for the deploy operation.
85 required: true
86 type: str
87 snapshot_name:
88 description:
89 - Sets the snapshot name to manage.
90 - This param or O(snapshot_id) is required only if O(state) is not C(remove_all)
91 type: str
92 snapshot_id:
93 description:
94 - Sets the snapshot id to manage.
95 - This param is available when O(state=absent) or O(state=revert).
96 type: int
97 version_added: 3.10.0
98 description:
99 description:
100 - Define an arbitrary description to attach to snapshot.
101 default: ''
102 type: str
103 quiesce:
104 description:
105 - If set to V(true) and virtual machine is powered on, it will quiesce the file system in virtual machine.
106 - Note that VMware Tools are required for this flag.
107 - If virtual machine is powered off or VMware Tools are not available, then this flag is set to V(false).
108 - If virtual machine does not provide capability to take quiesce snapshot, then this flag is set to V(false).
109 required: false
110 type: bool
111 default: false
112 memory_dump:
113 description:
114 - If set to V(true), memory dump of virtual machine is also included in snapshot.
115 - Note that memory snapshots take time and resources, this will take longer time to create.
116 - If virtual machine does not provide capability to take memory snapshot, then this flag is set to V(false).
117 required: false
118 type: bool
119 default: false
120 remove_children:
121 description:
122 - If set to V(true) and O(state=absent), then entire snapshot subtree is set for removal.
123 required: false
124 type: bool
125 default: false
126 new_snapshot_name:
127 description:
128 - Value to rename the existing snapshot to.
129 type: str
130 new_description:
131 description:
132 - Value to change the description of an existing snapshot to.
133 type: str
134 extends_documentation_fragment:
135 - vmware.vmware.base_options
136
137 '''
138
139 EXAMPLES = r'''
140 - name: Create a snapshot
141 community.vmware.vmware_guest_snapshot:
142 hostname: "{{ vcenter_hostname }}"
143 username: "{{ vcenter_username }}"
144 password: "{{ vcenter_password }}"
145 datacenter: "{{ datacenter_name }}"
146 folder: "/{{ datacenter_name }}/vm/"
147 name: "{{ guest_name }}"
148 state: present
149 snapshot_name: snap1
150 description: snap1_description
151 delegate_to: localhost
152
153 - name: Remove a snapshot
154 community.vmware.vmware_guest_snapshot:
155 hostname: "{{ vcenter_hostname }}"
156 username: "{{ vcenter_username }}"
157 password: "{{ vcenter_password }}"
158 datacenter: "{{ datacenter_name }}"
159 folder: "/{{ datacenter_name }}/vm/"
160 name: "{{ guest_name }}"
161 state: absent
162 snapshot_name: snap1
163 delegate_to: localhost
164
165 - name: Revert to a snapshot
166 community.vmware.vmware_guest_snapshot:
167 hostname: "{{ vcenter_hostname }}"
168 username: "{{ vcenter_username }}"
169 password: "{{ vcenter_password }}"
170 datacenter: "{{ datacenter_name }}"
171 folder: "/{{ datacenter_name }}/vm/"
172 name: "{{ guest_name }}"
173 state: revert
174 snapshot_name: snap1
175 delegate_to: localhost
176
177 - name: Remove all snapshots of a VM
178 community.vmware.vmware_guest_snapshot:
179 hostname: "{{ vcenter_hostname }}"
180 username: "{{ vcenter_username }}"
181 password: "{{ vcenter_password }}"
182 datacenter: "{{ datacenter_name }}"
183 folder: "/{{ datacenter_name }}/vm/"
184 name: "{{ guest_name }}"
185 state: remove_all
186 delegate_to: localhost
187
188 - name: Remove all snapshots of a VM using MoID
189 community.vmware.vmware_guest_snapshot:
190 hostname: "{{ vcenter_hostname }}"
191 username: "{{ vcenter_username }}"
192 password: "{{ vcenter_password }}"
193 datacenter: "{{ datacenter_name }}"
194 folder: "/{{ datacenter_name }}/vm/"
195 moid: vm-42
196 state: remove_all
197 delegate_to: localhost
198
199 - name: Take snapshot of a VM using quiesce and memory flag on
200 community.vmware.vmware_guest_snapshot:
201 hostname: "{{ vcenter_hostname }}"
202 username: "{{ vcenter_username }}"
203 password: "{{ vcenter_password }}"
204 datacenter: "{{ datacenter_name }}"
205 folder: "/{{ datacenter_name }}/vm/"
206 name: "{{ guest_name }}"
207 state: present
208 snapshot_name: dummy_vm_snap_0001
209 quiesce: true
210 memory_dump: true
211 delegate_to: localhost
212
213 - name: Remove a snapshot and snapshot subtree
214 community.vmware.vmware_guest_snapshot:
215 hostname: "{{ vcenter_hostname }}"
216 username: "{{ vcenter_username }}"
217 password: "{{ vcenter_password }}"
218 datacenter: "{{ datacenter_name }}"
219 folder: "/{{ datacenter_name }}/vm/"
220 name: "{{ guest_name }}"
221 state: absent
222 remove_children: true
223 snapshot_name: snap1
224 delegate_to: localhost
225
226 - name: Remove a snapshot with a snapshot id
227 community.vmware.vmware_guest_snapshot:
228 hostname: "{{ vcenter_hostname }}"
229 username: "{{ vcenter_username }}"
230 password: "{{ vcenter_password }}"
231 datacenter: "{{ datacenter_name }}"
232 folder: "/{{ datacenter_name }}/vm/"
233 name: "{{ guest_name }}"
234 snapshot_id: 10
235 state: absent
236 delegate_to: localhost
237
238 - name: Rename a snapshot
239 community.vmware.vmware_guest_snapshot:
240 hostname: "{{ vcenter_hostname }}"
241 username: "{{ vcenter_username }}"
242 password: "{{ vcenter_password }}"
243 datacenter: "{{ datacenter_name }}"
244 folder: "/{{ datacenter_name }}/vm/"
245 name: "{{ guest_name }}"
246 state: present
247 snapshot_name: current_snap_name
248 new_snapshot_name: im_renamed
249 new_description: "{{ new_snapshot_description }}"
250 delegate_to: localhost
251 '''
252
253 RETURN = r'''
254 snapshot_results:
255 description: metadata about the virtual machine snapshots
256 returned: always
257 type: dict
258 sample: {
259 "current_snapshot": {
260 "creation_time": "2019-04-09T14:40:26.617427+00:00",
261 "description": "Snapshot 4 example",
262 "id": 4,
263 "name": "snapshot4",
264 "state": "poweredOff"
265 },
266 "snapshots": [
267 {
268 "creation_time": "2019-04-09T14:38:24.667543+00:00",
269 "description": "Snapshot 3 example",
270 "id": 3,
271 "name": "snapshot3",
272 "state": "poweredOff"
273 },
274 {
275 "creation_time": "2019-04-09T14:40:26.617427+00:00",
276 "description": "Snapshot 4 example",
277 "id": 4,
278 "name": "snapshot4",
279 "state": "poweredOff"
280 }
281 ]
282 }
283 '''
284
285 import time
286 try:
287 from pyVmomi import vim
288 except ImportError:
289 pass
290
291 from ansible.module_utils.basic import AnsibleModule
292 from ansible.module_utils.common.text.converters import to_native
293 from ansible_collections.community.vmware.plugins.module_utils.vmware import PyVmomi, list_snapshots
294 from ansible_collections.vmware.vmware.plugins.module_utils.argument_spec import base_argument_spec
295
296
297 class PyVmomiHelper(PyVmomi):
298 def __init__(self, module):
299 super(PyVmomiHelper, self).__init__(module)
300
301 @staticmethod
302 def wait_for_task(task):
303 # https://www.vmware.com/support/developer/vc-sdk/visdk25pubs/ReferenceGuide/vim.Task.html
304 # https://www.vmware.com/support/developer/vc-sdk/visdk25pubs/ReferenceGuide/vim.TaskInfo.html
305 # https://github.com/virtdevninja/pyvmomi-community-samples/blob/master/samples/tools/tasks.py
306 while task.info.state not in ['success', 'error']:
307 time.sleep(1)
308
309 def get_snapshots_by_name_recursively(self, snapshots, snapname):
310 snap_obj = []
311 for snapshot in snapshots:
312 if snapshot.name == snapname:
313 snap_obj.append(snapshot)
314 else:
315 snap_obj = snap_obj + self.get_snapshots_by_name_recursively(snapshot.childSnapshotList, snapname)
316 return snap_obj
317
318 def get_snapshots_by_id_recursively(self, snapshots, snapid):
319 snap_obj = []
320 for snapshot in snapshots:
321 if snapshot.id == snapid:
322 snap_obj.append(snapshot)
323 else:
324 snap_obj = snap_obj + self.get_snapshots_by_id_recursively(snapshot.childSnapshotList, snapid)
325
326 return snap_obj
327
328 def snapshot_vm(self, vm):
329 memory_dump = False
330 quiesce = False
331 # Check if there is a latest snapshot already present as specified by user
332 if vm.snapshot is not None:
333 snap_obj = self.get_snapshots_by_name_recursively(vm.snapshot.rootSnapshotList,
334 self.module.params["snapshot_name"])
335 if snap_obj:
336 # Snapshot already exists, do not anything.
337 self.module.exit_json(changed=False,
338 msg="Snapshot named [%(snapshot_name)s] already exists and is current." % self.module.params)
339 # Check if Virtual Machine provides capabilities for Quiesce and Memory Snapshots
340 if vm.capability.quiescedSnapshotsSupported:
341 quiesce = self.module.params['quiesce']
342 if vm.capability.memorySnapshotsSupported:
343 memory_dump = self.module.params['memory_dump']
344
345 task = None
346 try:
347 task = vm.CreateSnapshot(self.module.params["snapshot_name"],
348 self.module.params["description"],
349 memory_dump,
350 quiesce)
351 except vim.fault.RestrictedVersion as exc:
352 self.module.fail_json(msg="Failed to take snapshot due to VMware Licence"
353 " restriction : %s" % to_native(exc.msg))
354 except Exception as exc:
355 self.module.fail_json(msg="Failed to create snapshot of virtual machine"
356 " %s due to %s" % (self.module.params['name'], to_native(exc)))
357 return task
358
359 def rename_snapshot(self, vm):
360 if vm.snapshot is None:
361 vm_id = self.module.params.get('uuid') or self.module.params.get('name') or self.params.get('moid')
362 self.module.fail_json(msg="virtual machine - %s doesn't have any snapshots" % vm_id)
363
364 snap_obj = self.get_snapshots_by_name_recursively(vm.snapshot.rootSnapshotList,
365 self.module.params["snapshot_name"])
366 task = None
367 if len(snap_obj) == 1:
368 snap_obj = snap_obj[0].snapshot
369 if self.module.params["new_snapshot_name"] and self.module.params["new_description"]:
370 task = snap_obj.RenameSnapshot(name=self.module.params["new_snapshot_name"],
371 description=self.module.params["new_description"])
372 elif self.module.params["new_snapshot_name"]:
373 task = snap_obj.RenameSnapshot(name=self.module.params["new_snapshot_name"])
374 else:
375 task = snap_obj.RenameSnapshot(description=self.module.params["new_description"])
376 else:
377 vm_id = self.module.params.get('uuid') or self.module.params.get('name') or self.params.get('moid')
378 self.module.exit_json(
379 msg="Couldn't find any snapshots with specified name: %s on VM: %s" %
380 (self.module.params["snapshot_name"], vm_id))
381 return task
382
383 def remove_or_revert_snapshot(self, vm):
384 if vm.snapshot is None:
385 vm_name = (self.module.params.get('uuid') or self.module.params.get('name'))
386 if self.module.params.get('state') == 'revert':
387 self.module.fail_json(msg="virtual machine - %s does not"
388 " have any snapshots to revert to." % vm_name)
389 self.module.exit_json(msg="virtual machine - %s doesn't have any"
390 " snapshots to remove." % vm_name)
391
392 if self.module.params["snapshot_name"]:
393 snap_obj = self.get_snapshots_by_name_recursively(vm.snapshot.rootSnapshotList,
394 self.module.params["snapshot_name"])
395 elif self.module.params["snapshot_id"]:
396 snap_obj = self.get_snapshots_by_id_recursively(vm.snapshot.rootSnapshotList,
397 self.module.params["snapshot_id"])
398
399 task = None
400 if len(snap_obj) == 1:
401 snap_obj = snap_obj[0].snapshot
402 if self.module.params["state"] == "absent":
403 # Remove subtree depending upon the user input
404 remove_children = self.module.params.get('remove_children', False)
405 task = snap_obj.RemoveSnapshot_Task(remove_children)
406 elif self.module.params["state"] == "revert":
407 task = snap_obj.RevertToSnapshot_Task()
408 else:
409 vm_id = self.module.params.get('uuid') or self.module.params.get('name') or self.params.get('moid')
410 self.module.exit_json(msg="Couldn't find any snapshots with"
411 " specified name: %s on VM: %s" % (self.module.params["snapshot_name"], vm_id))
412
413 return task
414
415 def apply_snapshot_op(self, vm):
416 result = {}
417 if self.module.params["state"] == "present":
418 if self.module.params["new_snapshot_name"] or self.module.params["new_description"]:
419 self.rename_snapshot(vm)
420 result = {'changed': True, 'failed': False, 'renamed': True}
421 task = None
422 else:
423 task = self.snapshot_vm(vm)
424 elif self.module.params["state"] in ["absent", "revert"]:
425 task = self.remove_or_revert_snapshot(vm)
426 elif self.module.params["state"] == "remove_all":
427 task = vm.RemoveAllSnapshots()
428 else:
429 # This should not happen
430 raise AssertionError()
431
432 if task:
433 self.wait_for_task(task)
434 if task.info.state == 'error':
435 result = {'changed': False, 'failed': True, 'msg': task.info.error.msg}
436 else:
437 result = {'changed': True, 'failed': False, 'snapshot_results': list_snapshots(vm)}
438
439 return result
440
441
442 def main():
443 argument_spec = base_argument_spec()
444 argument_spec.update(
445 state=dict(default='present', choices=['present', 'absent', 'revert', 'remove_all']),
446 name=dict(type='str'),
447 name_match=dict(type='str', choices=['first', 'last'], default='first'),
448 uuid=dict(type='str'),
449 moid=dict(type='str'),
450 use_instance_uuid=dict(type='bool', default=False),
451 folder=dict(type='str'),
452 datacenter=dict(required=True, type='str'),
453 snapshot_name=dict(type='str'),
454 snapshot_id=dict(type='int'),
455 description=dict(type='str', default=''),
456 quiesce=dict(type='bool', default=False),
457 memory_dump=dict(type='bool', default=False),
458 remove_children=dict(type='bool', default=False),
459 new_snapshot_name=dict(type='str'),
460 new_description=dict(type='str'),
461 )
462 module = AnsibleModule(
463 argument_spec=argument_spec,
464 required_together=[
465 ['name', 'folder']
466 ],
467 required_one_of=[
468 ['name', 'uuid', 'moid']
469 ],
470 mutually_exclusive=[
471 ['snapshot_name', 'snapshot_id']
472 ]
473 )
474
475 if module.params['folder']:
476 # FindByInventoryPath() does not require an absolute path
477 # so we should leave the input folder path unmodified
478 module.params['folder'] = module.params['folder'].rstrip('/')
479
480 pyv = PyVmomiHelper(module)
481 # Check if the VM exists before continuing
482 vm = pyv.get_vm()
483
484 if not vm:
485 vm_id = (module.params.get('uuid') or module.params.get('name') or module.params.get('moid'))
486 module.fail_json(msg="Unable to manage snapshots for non-existing VM %s" % vm_id)
487
488 if not (module.params['snapshot_name'] or module.params['snapshot_id']) and module.params['state'] != 'remove_all':
489 module.fail_json(msg="snapshot_name param is required when state is '%(state)s'" % module.params)
490
491 result = pyv.apply_snapshot_op(vm)
492
493 if 'failed' not in result:
494 result['failed'] = False
495
496 if result['failed']:
497 module.fail_json(**result)
498 else:
499 module.exit_json(**result)
500
501
502 if __name__ == '__main__':
503 main()