Debian Codegraph @

ansible_collections/vmware/vmware_rest/plugins/modules/vcenter_vm_guest_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_guest_power
12 short_description: Issues a request to the guest operating system asking it to perform
13 a soft shutdown, standby (suspend) or soft reboot
14 description: Issues a request to the guest operating system asking it to perform a
15 soft shutdown, standby (suspend) or soft reboot. This request returns immediately
16 and does not wait for the guest operating.
17 deprecated:
18 removed_in: 5.0.0
19 why: This module has been moved to the L(new vmware.vmware collection,https://forum.ansible.com/t/5880)
20 alternative: Use M(vmware.vmware.vm_powerstate) instead.
21 options:
22 session_timeout:
23 description:
24 - 'Timeout settings for client session. '
25 - 'The maximal number of seconds for the whole operation including connection
26 establishment, request sending and response. '
27 - The default value is 300s.
28 type: float
29 version_added: 2.1.0
30 state:
31 choices:
32 - reboot
33 - shutdown
34 - standby
35 description: []
36 required: true
37 type: str
38 vcenter_hostname:
39 description:
40 - The hostname or IP address of the vSphere vCenter
41 - If the value is not specified in the task, the value of environment variable
42 C(VMWARE_HOST) will be used instead.
43 required: true
44 type: str
45 vcenter_password:
46 description:
47 - The vSphere vCenter password
48 - If the value is not specified in the task, the value of environment variable
49 C(VMWARE_PASSWORD) will be used instead.
50 required: true
51 type: str
52 vcenter_rest_log_file:
53 description:
54 - 'You can use this optional parameter to set the location of a log file. '
55 - 'This file will be used to record the HTTP REST interaction. '
56 - 'The file will be stored on the host that runs the module. '
57 - 'If the value is not specified in the task, the value of '
58 - environment variable C(VMWARE_REST_LOG_FILE) will be used instead.
59 type: str
60 vcenter_username:
61 description:
62 - The vSphere vCenter username
63 - If the value is not specified in the task, the value of environment variable
64 C(VMWARE_USER) will be used instead.
65 required: true
66 type: str
67 vcenter_validate_certs:
68 default: true
69 description:
70 - Allows connection when SSL certificates are not valid. Set to C(false) when
71 certificates are not trusted.
72 - If the value is not specified in the task, the value of environment variable
73 C(VMWARE_VALIDATE_CERTS) will be used instead.
74 type: bool
75 vm:
76 description:
77 - Identifier of the virtual machine.
78 - The parameter must be the id of a resource returned by M(vmware.vmware_rest.vcenter_vm_info).
79 This parameter is mandatory.
80 required: true
81 type: str
82 author:
83 - Ansible Cloud Team (@ansible-collections)
84 version_added: 0.1.0
85 requirements:
86 - vSphere 7.0.3 or greater
87 - python >= 3.6
88 - aiohttp
89 seealso:
90 - description: A module to boot, hard shutdown and hard reset guest
91 module: vmware.vmware_rest.vcenter_vm_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: Shut down the VM
131 vmware.vmware_rest.vcenter_vm_guest_power:
132 state: shutdown
133 vm: '{{ my_vm.id }}'
134 """
135 RETURN = r"""
136 # content generated by the update_return_section callback# task: Shut down the VM
137 value:
138 description: Shut down the VM
139 returned: On success
140 sample: {}
141 type: dict
142 """
143
144
145 # This structure describes the format of the data expected by the end-points
146 PAYLOAD_FORMAT = {
147 "reboot": {"query": {}, "body": {}, "path": {"vm": "vm"}},
148 "shutdown": {"query": {}, "body": {}, "path": {"vm": "vm"}},
149 "standby": {"query": {}, "body": {}, "path": {"vm": "vm"}},
150 } # pylint: disable=line-too-long
151
152 from ansible.module_utils.basic import env_fallback
153 import os
154
155 if os.getenv("VMWARE_ENABLE_TURBO", False):
156 try:
157 from ansible_collections.cloud.common.plugins.module_utils.turbo.module import (
158 AnsibleTurboModule as AnsibleModule,
159 )
160
161 AnsibleModule.collection_name = "vmware.vmware_rest"
162 except ImportError:
163 from ansible.module_utils.basic import AnsibleModule
164 else:
165 from ansible.module_utils.basic import AnsibleModule
166
167 from ansible_collections.vmware.vmware_rest.plugins.module_utils.vmware_rest import (
168 exists,
169 gen_args,
170 get_subdevice_type,
171 open_session,
172 prepare_payload,
173 session_timeout,
174 update_changed_flag,
175 )
176
177
178 def prepare_argument_spec():
179 argument_spec = {
180 "vcenter_hostname": dict(
181 type="str",
182 required=True,
183 fallback=(env_fallback, ["VMWARE_HOST"]),
184 ),
185 "vcenter_username": dict(
186 type="str",
187 required=True,
188 fallback=(env_fallback, ["VMWARE_USER"]),
189 ),
190 "vcenter_password": dict(
191 type="str",
192 required=True,
193 no_log=True,
194 fallback=(env_fallback, ["VMWARE_PASSWORD"]),
195 ),
196 "vcenter_validate_certs": dict(
197 type="bool",
198 required=False,
199 default=True,
200 fallback=(env_fallback, ["VMWARE_VALIDATE_CERTS"]),
201 ),
202 "vcenter_rest_log_file": dict(
203 type="str",
204 required=False,
205 fallback=(env_fallback, ["VMWARE_REST_LOG_FILE"]),
206 ),
207 "session_timeout": dict(
208 type="float",
209 required=False,
210 fallback=(env_fallback, ["VMWARE_SESSION_TIMEOUT"]),
211 ),
212 }
213
214 argument_spec["state"] = {
215 "required": True,
216 "type": "str",
217 "choices": ["reboot", "shutdown", "standby"],
218 }
219 argument_spec["vm"] = {"required": True, "type": "str"}
220
221 return argument_spec
222
223
224 async def main():
225 required_if = list([])
226
227 module_args = prepare_argument_spec()
228 module = AnsibleModule(
229 argument_spec=module_args, required_if=required_if, supports_check_mode=False
230 )
231 if not module.params["vcenter_hostname"]:
232 module.fail_json("vcenter_hostname cannot be empty")
233 if not module.params["vcenter_username"]:
234 module.fail_json("vcenter_username cannot be empty")
235 if not module.params["vcenter_password"]:
236 module.fail_json("vcenter_password cannot be empty")
237 try:
238 session = await open_session(
239 vcenter_hostname=module.params["vcenter_hostname"],
240 vcenter_username=module.params["vcenter_username"],
241 vcenter_password=module.params["vcenter_password"],
242 validate_certs=module.params["vcenter_validate_certs"],
243 log_file=module.params["vcenter_rest_log_file"],
244 )
245 except Exception as err:
246 if hasattr(err, "get_message"):
247 module.fail_json(err.get_message())
248 else:
249 module.fail_json(str(err))
250 result = await entry_point(module, session)
251 module.exit_json(**result)
252
253
254 # template: default_module.j2
255 def build_url(params):
256 return ("https://{vcenter_hostname}" "/api/vcenter/vm/{vm}/guest/power").format(
257 **params
258 )
259
260
261 async def entry_point(module, session):
262
263 if module.params["state"] == "present":
264 if "_create" in globals():
265 operation = "create"
266 else:
267 operation = "update"
268 elif module.params["state"] == "absent":
269 operation = "delete"
270 else:
271 operation = module.params["state"]
272
273 func = globals()["_" + operation]
274
275 return await func(module.params, session)
276
277
278 async def _reboot(params, session):
279 _in_query_parameters = PAYLOAD_FORMAT["reboot"]["query"].keys()
280 payload = prepare_payload(params, PAYLOAD_FORMAT["reboot"])
281 subdevice_type = get_subdevice_type(
282 "/api/vcenter/vm/{vm}/guest/power?action=reboot"
283 )
284 if subdevice_type and not params[subdevice_type]:
285 _json = await exists(params, session, build_url(params))
286 if _json:
287 params[subdevice_type] = _json["id"]
288 _url = (
289 "https://{vcenter_hostname}"
290 # aa
291 "/api/vcenter/vm/{vm}/guest/power?action=reboot"
292 ).format(**params) + gen_args(params, _in_query_parameters)
293 async with session.post(_url, json=payload, **session_timeout(params)) as resp:
294 try:
295 if resp.headers["Content-Type"] == "application/json":
296 _json = await resp.json()
297 except KeyError:
298 _json = {}
299 if "value" not in _json: # 7.0.2
300 _json = {"value": _json}
301
302 return await update_changed_flag(_json, resp.status, "reboot")
303
304
305 async def _shutdown(params, session):
306 _in_query_parameters = PAYLOAD_FORMAT["shutdown"]["query"].keys()
307 payload = prepare_payload(params, PAYLOAD_FORMAT["shutdown"])
308 subdevice_type = get_subdevice_type(
309 "/api/vcenter/vm/{vm}/guest/power?action=shutdown"
310 )
311 if subdevice_type and not params[subdevice_type]:
312 _json = await exists(params, session, build_url(params))
313 if _json:
314 params[subdevice_type] = _json["id"]
315 _url = (
316 "https://{vcenter_hostname}"
317 # aa
318 "/api/vcenter/vm/{vm}/guest/power?action=shutdown"
319 ).format(**params) + gen_args(params, _in_query_parameters)
320 async with session.post(_url, json=payload, **session_timeout(params)) as resp:
321 try:
322 if resp.headers["Content-Type"] == "application/json":
323 _json = await resp.json()
324 except KeyError:
325 _json = {}
326 if "value" not in _json: # 7.0.2
327 _json = {"value": _json}
328
329 return await update_changed_flag(_json, resp.status, "shutdown")
330
331
332 async def _standby(params, session):
333 _in_query_parameters = PAYLOAD_FORMAT["standby"]["query"].keys()
334 payload = prepare_payload(params, PAYLOAD_FORMAT["standby"])
335 subdevice_type = get_subdevice_type(
336 "/api/vcenter/vm/{vm}/guest/power?action=standby"
337 )
338 if subdevice_type and not params[subdevice_type]:
339 _json = await exists(params, session, build_url(params))
340 if _json:
341 params[subdevice_type] = _json["id"]
342 _url = (
343 "https://{vcenter_hostname}"
344 # aa
345 "/api/vcenter/vm/{vm}/guest/power?action=standby"
346 ).format(**params) + gen_args(params, _in_query_parameters)
347 async with session.post(_url, json=payload, **session_timeout(params)) as resp:
348 try:
349 if resp.headers["Content-Type"] == "application/json":
350 _json = await resp.json()
351 except KeyError:
352 _json = {}
353 if "value" not in _json: # 7.0.2
354 _json = {"value": _json}
355
356 return await update_changed_flag(_json, resp.status, "standby")
357
358
359 if __name__ == "__main__":
360 import asyncio
361
362 current_loop = asyncio.new_event_loop()
363 try:
364 asyncio.set_event_loop(current_loop)
365 current_loop.run_until_complete(main())
366 finally:
367 current_loop.close()