Debian Codegraph @

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

raw
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3
4 # Copyright: (c) 2018, Jose Angel Munoz <josea.munoz () gmail.com>
5 # Copyright: (c) 2018, Ansible Project
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_move
16 short_description: Moves virtual machines in vCenter
17 description:
18 - This module can be used to move virtual machines between folders.
19 author:
20 - Jose Angel Munoz (@imjoseangel)
21 options:
22 name:
23 description:
24 - Name of the existing virtual machine to move.
25 - This is required if O(uuid) or O(moid) is not supplied.
26 type: str
27 uuid:
28 description:
29 - UUID of the virtual machine to manage if known, this is VMware's unique identifier.
30 - This is required if O(name) or O(moid) is not supplied.
31 type: str
32 moid:
33 description:
34 - Managed Object ID of the instance to manage if known, this is a unique identifier only within a single vCenter instance.
35 - This is required if O(name) or O(uuid) is not supplied.
36 type: str
37 use_instance_uuid:
38 description:
39 - Whether to use the VMware instance UUID rather than the BIOS UUID.
40 default: false
41 type: bool
42 name_match:
43 description:
44 - If multiple virtual machines matching the name, use the first or last found.
45 default: 'first'
46 choices: [ first, last ]
47 type: str
48 dest_folder:
49 description:
50 - Absolute path to move an existing guest
51 - The dest_folder should include the datacenter. ESX's datacenter is ha-datacenter.
52 - 'Examples:'
53 - ' dest_folder: /ha-datacenter/vm'
54 - ' dest_folder: ha-datacenter/vm'
55 - ' dest_folder: /datacenter1/vm'
56 - ' dest_folder: datacenter1/vm'
57 - ' dest_folder: /datacenter1/vm/folder1'
58 - ' dest_folder: datacenter1/vm/folder1'
59 - ' dest_folder: /folder1/datacenter1/vm'
60 - ' dest_folder: folder1/datacenter1/vm'
61 - ' dest_folder: /folder1/datacenter1/vm/folder2'
62 required: true
63 type: str
64 datacenter:
65 description:
66 - Destination datacenter for the move operation
67 required: true
68 type: str
69 extends_documentation_fragment:
70 - vmware.vmware.base_options
71
72 '''
73
74 EXAMPLES = r'''
75 - name: Move Virtual Machine
76 community.vmware.vmware_guest_move:
77 hostname: "{{ vcenter_hostname }}"
78 username: "{{ vcenter_username }}"
79 password: "{{ vcenter_password }}"
80 datacenter: datacenter
81 name: testvm-1
82 dest_folder: "/{{ datacenter }}/vm"
83 delegate_to: localhost
84
85 - name: Move Virtual Machine using MoID
86 community.vmware.vmware_guest_move:
87 hostname: "{{ vcenter_hostname }}"
88 username: "{{ vcenter_username }}"
89 password: "{{ vcenter_password }}"
90 datacenter: datacenter
91 moid: vm-42
92 dest_folder: "/{{ datacenter }}/vm"
93 delegate_to: localhost
94
95 - name: Get VM UUID
96 vmware_guest_facts:
97 hostname: "{{ vcenter_hostname }}"
98 username: "{{ vcenter_username }}"
99 password: "{{ vcenter_password }}"
100 datacenter: "{{ datacenter }}"
101 folder: "/{{ datacenter }}/vm"
102 name: "{{ vm_name }}"
103 delegate_to: localhost
104 register: vm_facts
105
106 - name: Get UUID from previous task and pass it to this task
107 community.vmware.vmware_guest_move:
108 hostname: "{{ vcenter_hostname }}"
109 username: "{{ vcenter_username }}"
110 password: "{{ vcenter_password }}"
111 datacenter: "{{ datacenter }}"
112 uuid: "{{ vm_facts.instance.hw_product_uuid }}"
113 dest_folder: "/DataCenter/vm/path/to/new/folder/where/we/want"
114 delegate_to: localhost
115 register: facts
116 '''
117
118 RETURN = r'''
119 instance:
120 description: metadata about the virtual machine
121 returned: always
122 type: dict
123 sample: {
124 "annotation": null,
125 "current_snapshot": null,
126 "customvalues": {},
127 "guest_consolidation_needed": false,
128 "guest_question": null,
129 "guest_tools_status": null,
130 "guest_tools_version": "0",
131 "hw_cores_per_socket": 1,
132 "hw_datastores": [
133 "LocalDS_0"
134 ],
135 "hw_esxi_host": "DC0_H0",
136 "hw_eth0": {
137 "addresstype": "generated",
138 "ipaddresses": null,
139 "label": "ethernet-0",
140 "macaddress": "00:0c:29:6b:34:2c",
141 "macaddress_dash": "00-0c-29-6b-34-2c",
142 "summary": "DVSwitch: 43cdd1db-1ef7-4016-9bbe-d96395616199"
143 },
144 "hw_files": [
145 "[LocalDS_0] DC0_H0_VM0/DC0_H0_VM0.vmx"
146 ],
147 "hw_folder": "/F0/DC0/vm/F0",
148 "hw_guest_full_name": null,
149 "hw_guest_ha_state": null,
150 "hw_guest_id": "otherGuest",
151 "hw_interfaces": [
152 "eth0"
153 ],
154 "hw_is_template": false,
155 "hw_memtotal_mb": 32,
156 "hw_name": "DC0_H0_VM0",
157 "hw_power_status": "poweredOn",
158 "hw_processor_count": 1,
159 "hw_product_uuid": "581c2808-64fb-45ee-871f-6a745525cb29",
160 "instance_uuid": "8bcb0b6e-3a7d-4513-bf6a-051d15344352",
161 "ipv4": null,
162 "ipv6": null,
163 "module_hw": true,
164 "snapshots": []
165 }
166 '''
167
168 from ansible.module_utils.basic import AnsibleModule
169 from ansible.module_utils.common.text.converters import to_native
170 from ansible_collections.community.vmware.plugins.module_utils.vmware import PyVmomi, wait_for_task
171 from ansible_collections.vmware.vmware.plugins.module_utils.argument_spec import base_argument_spec
172
173
174 class PyVmomiHelper(PyVmomi):
175 def __init__(self, module):
176 super(PyVmomiHelper, self).__init__(module)
177
178
179 def main():
180 argument_spec = base_argument_spec()
181 argument_spec.update(
182 name=dict(type='str'),
183 name_match=dict(
184 type='str', choices=['first', 'last'], default='first'),
185 uuid=dict(type='str'),
186 moid=dict(type='str'),
187 use_instance_uuid=dict(type='bool', default=False),
188 dest_folder=dict(type='str', required=True),
189 datacenter=dict(type='str', required=True),
190 )
191 module = AnsibleModule(
192 argument_spec=argument_spec,
193 required_one_of=[
194 ['name', 'uuid', 'moid']
195 ],
196 mutually_exclusive=[
197 ['name', 'uuid', 'moid']
198 ],
199 supports_check_mode=True
200 )
201
202 # FindByInventoryPath() does not require an absolute path
203 # so we should leave the input folder path unmodified
204 module.params['dest_folder'] = module.params['dest_folder'].rstrip('/')
205 pyv = PyVmomiHelper(module)
206 search_index = pyv.content.searchIndex
207
208 # Check if the VM exists before continuing
209 vm = pyv.get_vm()
210
211 # VM exists
212 if vm:
213 try:
214 vm_path = pyv.get_vm_path(pyv.content, vm).lstrip('/')
215 if module.params['name']:
216 vm_name = module.params['name']
217 else:
218 vm_name = vm.name
219
220 vm_full = vm_path + '/' + vm_name
221 folder = search_index.FindByInventoryPath(module.params['dest_folder'])
222 if folder is None:
223 module.fail_json(msg="Folder name and/or path does not exist")
224 vm_to_move = search_index.FindByInventoryPath(vm_full)
225 if module.check_mode:
226 module.exit_json(changed=True, instance=pyv.gather_facts(vm))
227 if vm_path != module.params['dest_folder'].lstrip('/'):
228 move_task = folder.MoveInto([vm_to_move])
229 changed, err = wait_for_task(move_task)
230 if changed:
231 module.exit_json(
232 changed=True, instance=pyv.gather_facts(vm))
233 else:
234 module.exit_json(instance=pyv.gather_facts(vm))
235 except Exception as exc:
236 module.fail_json(msg="Failed to move VM with exception %s" %
237 to_native(exc))
238 else:
239 if module.check_mode:
240 module.exit_json(changed=False)
241 vm_id = (module.params.get('uuid') or module.params.get('name') or module.params.get('moid'))
242 module.fail_json(msg="Unable to find VM %s to move to %s" % (vm_id, module.params.get('dest_folder')))
243
244
245 if __name__ == '__main__':
246 main()