Debian Codegraph @

ansible_collections/vmware/vmware_rest/plugins/modules/vcenter_vm_power.py

raw
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3 # Copyright: (c) 2021, Ansible Project
4 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
5 # template: header.j2
6 # This module is autogenerated using the ansible.content_builder.
7 # See: https://github.com/ansible-community/ansible.content_builder
8
9
10 DOCUMENTATION = r"""
11 module: vcenter_vm_power
12 short_description: Operate a boot, hard shutdown, hard reset or hard suspend on a
13 guest.
14 description: Ask the vCenter to boot, force shutdown or force reset a guest.
15 deprecated:
16 removed_in: 5.0.0
17 why: This module has been moved to the L(new vmware.vmware collection,https://forum.ansible.com/t/5880)
18 alternative: Use M(vmware.vmware.vm_powerstate) instead.
19 options:
20 session_timeout:
21 description:
22 - 'Timeout settings for client session. '
23 - 'The maximal number of seconds for the whole operation including connection
24 establishment, request sending and response. '
25 - The default value is 300s.
26 type: float
27 version_added: 2.1.0
28 state:
29 choices:
30 - reset
31 - start
32 - stop
33 - suspend
34 description: []
35 required: true
36 type: str
37 vcenter_hostname:
38 description:
39 - The hostname or IP address of the vSphere vCenter
40 - If the value is not specified in the task, the value of environment variable
41 C(VMWARE_HOST) will be used instead.
42 required: true
43 type: str
44 vcenter_password:
45 description:
46 - The vSphere vCenter password
47 - If the value is not specified in the task, the value of environment variable
48 C(VMWARE_PASSWORD) will be used instead.
49 required: true
50 type: str
51 vcenter_rest_log_file:
52 description:
53 - 'You can use this optional parameter to set the location of a log file. '
54 - 'This file will be used to record the HTTP REST interaction. '
55 - 'The file will be stored on the host that runs the module. '
56 - 'If the value is not specified in the task, the value of '
57 - environment variable C(VMWARE_REST_LOG_FILE) will be used instead.
58 type: str
59 vcenter_username:
60 description:
61 - The vSphere vCenter username
62 - If the value is not specified in the task, the value of environment variable
63 C(VMWARE_USER) will be used instead.
64 required: true
65 type: str
66 vcenter_validate_certs:
67 default: true
68 description:
69 - Allows connection when SSL certificates are not valid. Set to C(false) when
70 certificates are not trusted.
71 - If the value is not specified in the task, the value of environment variable
72 C(VMWARE_VALIDATE_CERTS) will be used instead.
73 type: bool
74 vm:
75 description:
76 - Virtual machine identifier.
77 - The parameter must be the id of a resource returned by M(vmware.vmware_rest.vcenter_vm_info).
78 This parameter is mandatory.
79 required: true
80 type: str
81 author:
82 - Ansible Cloud Team (@ansible-collections)
83 version_added: 0.1.0
84 requirements:
85 - vSphere 7.0.3 or greater
86 - python >= 3.6
87 - aiohttp
88 seealso:
89 - description: Issues a request to the guest operating system asking it to perform
90 a soft shutdown, standby (suspend) or soft reboot
91 module: vmware.vmware_rest.vcenter_vm_guest_power
92 notes:
93 - Tested on vSphere 7.0.3
94 """
95
96 EXAMPLES = r"""
97 - name: Create a VM
98 vmware.vmware_rest.vcenter_vm:
99 placement:
100 cluster: "{{ lookup('vmware.vmware_rest.cluster_moid', '/my_dc/host/my_cluster') }}"
101 datastore: "{{ lookup('vmware.vmware_rest.datastore_moid', '/my_dc/datastore/local') }}"
102 folder: "{{ lookup('vmware.vmware_rest.folder_moid', '/my_dc/vm') }}"
103 resource_pool: "{{ lookup('vmware.vmware_rest.resource_pool_moid', '/my_dc/host/my_cluster/Resources') }}"
104 name: test_vm1
105 guest_OS: RHEL_7_64
106 hardware_version: VMX_11
107 memory:
108 hot_add_enabled: true
109 size_MiB: 1024
110 disks:
111 - type: SATA
112 backing:
113 type: VMDK_FILE
114 vmdk_file: '[local] test_vm1/{{ disk_name }}.vmdk'
115 - type: SATA
116 new_vmdk:
117 name: second_disk
118 capacity: 32000000000
119 cdroms:
120 - type: SATA
121 sata:
122 bus: 0
123 unit: 2
124 nics:
125 - backing:
126 type: STANDARD_PORTGROUP
127 network: "{{ lookup('vmware.vmware_rest.network_moid', '/my_dc/network/VM Network') }}"
128 register: my_vm
129
130 - name: Turn the power of the VM on
131 vmware.vmware_rest.vcenter_vm_power:
132 state: start
133 vm: '{{ my_vm.id }}'
134
135 - name: Turn on the power of the VM
136 vmware.vmware_rest.vcenter_vm_power:
137 state: start
138 vm: '{{ my_vm.id }}'
139
140 - name: Look up the VM called test_vm1 in the inventory
141 register: search_result
142 vmware.vmware_rest.vcenter_vm_info:
143 filter_names:
144 - test_vm1
145
146 - name: Collect information about a specific VM
147 vmware.vmware_rest.vcenter_vm_info:
148 vm: '{{ search_result.value[0].vm }}'
149 register: test_vm1_info
150
151 - name: Turn the power of the VM on
152 vmware.vmware_rest.vcenter_vm_power:
153 state: start
154 vm: '{{ test_vm1_info.id }}'
155 """
156 RETURN = r"""
157 # content generated by the update_return_section callback# task: Turn off the VM
158 msg:
159 description: Turn off the VM
160 returned: On success
161 sample: All items completed
162 type: str
163 results:
164 description: Turn off the VM
165 returned: On success
166 sample:
167 - _ansible_item_label:
168 cpu_count: 1
169 memory_size_MiB: 128
170 name: vCLS-e89f3630-0f4d-4adb-bac5-1912e2b5d8ab
171 power_state: POWERED_OFF
172 vm: vm-1023
173 _ansible_no_log: null
174 ansible_loop_var: item
175 changed: 0
176 failed: 0
177 invocation:
178 module_args:
179 session_timeout: null
180 state: stop
181 vcenter_hostname: vcenter.test
182 vcenter_password: VALUE_SPECIFIED_IN_NO_LOG_PARAMETER
183 vcenter_rest_log_file: /tmp/vmware_rest.log
184 vcenter_username: [email protected]
185 vcenter_validate_certs: 0
186 vm: vm-1023
187 item:
188 cpu_count: 1
189 memory_size_MiB: 128
190 name: vCLS-e89f3630-0f4d-4adb-bac5-1912e2b5d8ab
191 power_state: POWERED_OFF
192 vm: vm-1023
193 value:
194 error_type: ALREADY_IN_DESIRED_STATE
195 messages:
196 - args: []
197 default_message: Virtual machine is already powered off.
198 id: com.vmware.api.vcenter.vm.power.already_powered_off
199 - args: []
200 default_message: The attempted operation cannot be performed in the current
201 state (Powered off).
202 id: vmsg.InvalidPowerState.summary
203 - _ansible_item_label:
204 cpu_count: 1
205 memory_size_MiB: 1080
206 name: test_vm1
207 power_state: POWERED_ON
208 vm: vm-1024
209 _ansible_no_log: null
210 ansible_loop_var: item
211 changed: 0
212 failed: 0
213 invocation:
214 module_args:
215 session_timeout: null
216 state: stop
217 vcenter_hostname: vcenter.test
218 vcenter_password: VALUE_SPECIFIED_IN_NO_LOG_PARAMETER
219 vcenter_rest_log_file: /tmp/vmware_rest.log
220 vcenter_username: [email protected]
221 vcenter_validate_certs: 0
222 vm: vm-1024
223 item:
224 cpu_count: 1
225 memory_size_MiB: 1080
226 name: test_vm1
227 power_state: POWERED_ON
228 vm: vm-1024
229 value: {}
230 type: list
231 """
232
233
234 # This structure describes the format of the data expected by the end-points
235 PAYLOAD_FORMAT = {
236 "reset": {"query": {}, "body": {}, "path": {"vm": "vm"}},
237 "stop": {"query": {}, "body": {}, "path": {"vm": "vm"}},
238 "start": {"query": {}, "body": {}, "path": {"vm": "vm"}},
239 "suspend": {"query": {}, "body": {}, "path": {"vm": "vm"}},
240 } # pylint: disable=line-too-long
241
242 from ansible.module_utils.basic import env_fallback
243 import os
244
245 if os.getenv("VMWARE_ENABLE_TURBO", False):
246 try:
247 from ansible_collections.cloud.common.plugins.module_utils.turbo.module import (
248 AnsibleTurboModule as AnsibleModule,
249 )
250
251 AnsibleModule.collection_name = "vmware.vmware_rest"
252 except ImportError:
253 from ansible.module_utils.basic import AnsibleModule
254 else:
255 from ansible.module_utils.basic import AnsibleModule
256
257 from ansible_collections.vmware.vmware_rest.plugins.module_utils.vmware_rest import (
258 exists,
259 gen_args,
260 get_subdevice_type,
261 open_session,
262 prepare_payload,
263 session_timeout,
264 update_changed_flag,
265 )
266
267
268 def prepare_argument_spec():
269 argument_spec = {
270 "vcenter_hostname": dict(
271 type="str",
272 required=True,
273 fallback=(env_fallback, ["VMWARE_HOST"]),
274 ),
275 "vcenter_username": dict(
276 type="str",
277 required=True,
278 fallback=(env_fallback, ["VMWARE_USER"]),
279 ),
280 "vcenter_password": dict(
281 type="str",
282 required=True,
283 no_log=True,
284 fallback=(env_fallback, ["VMWARE_PASSWORD"]),
285 ),
286 "vcenter_validate_certs": dict(
287 type="bool",
288 required=False,
289 default=True,
290 fallback=(env_fallback, ["VMWARE_VALIDATE_CERTS"]),
291 ),
292 "vcenter_rest_log_file": dict(
293 type="str",
294 required=False,
295 fallback=(env_fallback, ["VMWARE_REST_LOG_FILE"]),
296 ),
297 "session_timeout": dict(
298 type="float",
299 required=False,
300 fallback=(env_fallback, ["VMWARE_SESSION_TIMEOUT"]),
301 ),
302 }
303
304 argument_spec["state"] = {
305 "required": True,
306 "type": "str",
307 "choices": ["reset", "start", "stop", "suspend"],
308 }
309 argument_spec["vm"] = {"required": True, "type": "str"}
310
311 return argument_spec
312
313
314 async def main():
315 required_if = list([])
316
317 module_args = prepare_argument_spec()
318 module = AnsibleModule(
319 argument_spec=module_args, required_if=required_if, supports_check_mode=False
320 )
321 if not module.params["vcenter_hostname"]:
322 module.fail_json("vcenter_hostname cannot be empty")
323 if not module.params["vcenter_username"]:
324 module.fail_json("vcenter_username cannot be empty")
325 if not module.params["vcenter_password"]:
326 module.fail_json("vcenter_password cannot be empty")
327 try:
328 session = await open_session(
329 vcenter_hostname=module.params["vcenter_hostname"],
330 vcenter_username=module.params["vcenter_username"],
331 vcenter_password=module.params["vcenter_password"],
332 validate_certs=module.params["vcenter_validate_certs"],
333 log_file=module.params["vcenter_rest_log_file"],
334 )
335 except Exception as err:
336 if hasattr(err, "get_message"):
337 module.fail_json(err.get_message())
338 else:
339 module.fail_json(str(err))
340 result = await entry_point(module, session)
341 module.exit_json(**result)
342
343
344 # template: default_module.j2
345 def build_url(params):
346 return ("https://{vcenter_hostname}" "/api/vcenter/vm/{vm}/power").format(**params)
347
348
349 async def entry_point(module, session):
350
351 if module.params["state"] == "present":
352 if "_create" in globals():
353 operation = "create"
354 else:
355 operation = "update"
356 elif module.params["state"] == "absent":
357 operation = "delete"
358 else:
359 operation = module.params["state"]
360
361 func = globals()["_" + operation]
362
363 return await func(module.params, session)
364
365
366 async def _reset(params, session):
367 _in_query_parameters = PAYLOAD_FORMAT["reset"]["query"].keys()
368 payload = prepare_payload(params, PAYLOAD_FORMAT["reset"])
369 subdevice_type = get_subdevice_type("/api/vcenter/vm/{vm}/power?action=reset")
370 if subdevice_type and not params[subdevice_type]:
371 _json = await exists(params, session, build_url(params))
372 if _json:
373 params[subdevice_type] = _json["id"]
374 _url = (
375 "https://{vcenter_hostname}"
376 # aa
377 "/api/vcenter/vm/{vm}/power?action=reset"
378 ).format(**params) + gen_args(params, _in_query_parameters)
379 async with session.post(_url, json=payload, **session_timeout(params)) as resp:
380 try:
381 if resp.headers["Content-Type"] == "application/json":
382 _json = await resp.json()
383 except KeyError:
384 _json = {}
385 if "value" not in _json: # 7.0.2
386 _json = {"value": _json}
387
388 return await update_changed_flag(_json, resp.status, "reset")
389
390
391 async def _start(params, session):
392 _in_query_parameters = PAYLOAD_FORMAT["start"]["query"].keys()
393 payload = prepare_payload(params, PAYLOAD_FORMAT["start"])
394 subdevice_type = get_subdevice_type("/api/vcenter/vm/{vm}/power?action=start")
395 if subdevice_type and not params[subdevice_type]:
396 _json = await exists(params, session, build_url(params))
397 if _json:
398 params[subdevice_type] = _json["id"]
399 _url = (
400 "https://{vcenter_hostname}"
401 # aa
402 "/api/vcenter/vm/{vm}/power?action=start"
403 ).format(**params) + gen_args(params, _in_query_parameters)
404 async with session.post(_url, json=payload, **session_timeout(params)) as resp:
405 try:
406 if resp.headers["Content-Type"] == "application/json":
407 _json = await resp.json()
408 except KeyError:
409 _json = {}
410 if "value" not in _json: # 7.0.2
411 _json = {"value": _json}
412
413 return await update_changed_flag(_json, resp.status, "start")
414
415
416 async def _stop(params, session):
417 _in_query_parameters = PAYLOAD_FORMAT["stop"]["query"].keys()
418 payload = prepare_payload(params, PAYLOAD_FORMAT["stop"])
419 subdevice_type = get_subdevice_type("/api/vcenter/vm/{vm}/power?action=stop")
420 if subdevice_type and not params[subdevice_type]:
421 _json = await exists(params, session, build_url(params))
422 if _json:
423 params[subdevice_type] = _json["id"]
424 _url = (
425 "https://{vcenter_hostname}"
426 # aa
427 "/api/vcenter/vm/{vm}/power?action=stop"
428 ).format(**params) + gen_args(params, _in_query_parameters)
429 async with session.post(_url, json=payload, **session_timeout(params)) as resp:
430 try:
431 if resp.headers["Content-Type"] == "application/json":
432 _json = await resp.json()
433 except KeyError:
434 _json = {}
435 if "value" not in _json: # 7.0.2
436 _json = {"value": _json}
437
438 return await update_changed_flag(_json, resp.status, "stop")
439
440
441 async def _suspend(params, session):
442 _in_query_parameters = PAYLOAD_FORMAT["suspend"]["query"].keys()
443 payload = prepare_payload(params, PAYLOAD_FORMAT["suspend"])
444 subdevice_type = get_subdevice_type("/api/vcenter/vm/{vm}/power?action=suspend")
445 if subdevice_type and not params[subdevice_type]:
446 _json = await exists(params, session, build_url(params))
447 if _json:
448 params[subdevice_type] = _json["id"]
449 _url = (
450 "https://{vcenter_hostname}"
451 # aa
452 "/api/vcenter/vm/{vm}/power?action=suspend"
453 ).format(**params) + gen_args(params, _in_query_parameters)
454 async with session.post(_url, json=payload, **session_timeout(params)) as resp:
455 try:
456 if resp.headers["Content-Type"] == "application/json":
457 _json = await resp.json()
458 except KeyError:
459 _json = {}
460 if "value" not in _json: # 7.0.2
461 _json = {"value": _json}
462
463 return await update_changed_flag(_json, resp.status, "suspend")
464
465
466 if __name__ == "__main__":
467 import asyncio
468
469 current_loop = asyncio.new_event_loop()
470 try:
471 asyncio.set_event_loop(current_loop)
472 current_loop.run_until_complete(main())
473 finally:
474 current_loop.close()