Debian Codegraph @

ansible_collections/vmware/vmware_rest/plugins/modules/appliance_shutdown.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: appliance_shutdown
12 short_description: Cancel pending shutdown action.
13 description: Cancel pending shutdown action.
14 options:
15 delay:
16 description:
17 - Minutes after which poweroff should start. If 0 is specified, poweroff will
18 start immediately. Required with I(state=['poweroff', 'reboot'])
19 type: int
20 reason:
21 description:
22 - Reason for peforming poweroff. Required with I(state=['poweroff', 'reboot'])
23 type: str
24 session_timeout:
25 description:
26 - 'Timeout settings for client session. '
27 - 'The maximal number of seconds for the whole operation including connection
28 establishment, request sending and response. '
29 - The default value is 300s.
30 type: float
31 version_added: 2.1.0
32 state:
33 choices:
34 - cancel
35 - poweroff
36 - reboot
37 description: []
38 required: true
39 type: str
40 vcenter_hostname:
41 description:
42 - The hostname or IP address of the vSphere vCenter
43 - If the value is not specified in the task, the value of environment variable
44 C(VMWARE_HOST) will be used instead.
45 required: true
46 type: str
47 vcenter_password:
48 description:
49 - The vSphere vCenter password
50 - If the value is not specified in the task, the value of environment variable
51 C(VMWARE_PASSWORD) will be used instead.
52 required: true
53 type: str
54 vcenter_rest_log_file:
55 description:
56 - 'You can use this optional parameter to set the location of a log file. '
57 - 'This file will be used to record the HTTP REST interaction. '
58 - 'The file will be stored on the host that runs the module. '
59 - 'If the value is not specified in the task, the value of '
60 - environment variable C(VMWARE_REST_LOG_FILE) will be used instead.
61 type: str
62 vcenter_username:
63 description:
64 - The vSphere vCenter username
65 - If the value is not specified in the task, the value of environment variable
66 C(VMWARE_USER) will be used instead.
67 required: true
68 type: str
69 vcenter_validate_certs:
70 default: true
71 description:
72 - Allows connection when SSL certificates are not valid. Set to C(false) when
73 certificates are not trusted.
74 - If the value is not specified in the task, the value of environment variable
75 C(VMWARE_VALIDATE_CERTS) will be used instead.
76 type: bool
77 author:
78 - Ansible Cloud Team (@ansible-collections)
79 version_added: 2.0.0
80 requirements:
81 - vSphere 7.0.3 or greater
82 - python >= 3.6
83 - aiohttp
84 notes:
85 - Tested on vSphere 7.0.3
86 """
87
88 EXAMPLES = r"""
89 - name: Shutdown the appliance
90 vmware.vmware_rest.appliance_shutdown:
91 state: poweroff
92 reason: this is an example
93 delay: 600
94 register: result
95
96 - name: Abort the shutdown of the appliance
97 vmware.vmware_rest.appliance_shutdown:
98 state: cancel
99 register: result
100
101 - name: Reboot the appliance
102 vmware.vmware_rest.appliance_shutdown:
103 state: reboot
104 reason: this is an example
105 delay: 600
106 register: result
107
108 - name: Abort the reboot
109 vmware.vmware_rest.appliance_shutdown:
110 state: cancel
111 register: result
112 """
113 RETURN = r"""
114 # content generated by the update_return_section callback# task: Abort the reboot
115 value:
116 description: Abort the reboot
117 returned: On success
118 sample: {}
119 type: dict
120 """
121
122
123 # This structure describes the format of the data expected by the end-points
124 PAYLOAD_FORMAT = {
125 "reboot": {"query": {}, "body": {"delay": "delay", "reason": "reason"}, "path": {}},
126 "cancel": {"query": {}, "body": {}, "path": {}},
127 "poweroff": {
128 "query": {},
129 "body": {"delay": "delay", "reason": "reason"},
130 "path": {},
131 },
132 } # pylint: disable=line-too-long
133
134 from ansible.module_utils.basic import env_fallback
135 import os
136
137 if os.getenv("VMWARE_ENABLE_TURBO", False):
138 try:
139 from ansible_collections.cloud.common.plugins.module_utils.turbo.module import (
140 AnsibleTurboModule as AnsibleModule,
141 )
142
143 AnsibleModule.collection_name = "vmware.vmware_rest"
144 except ImportError:
145 from ansible.module_utils.basic import AnsibleModule
146 else:
147 from ansible.module_utils.basic import AnsibleModule
148
149 from ansible_collections.vmware.vmware_rest.plugins.module_utils.vmware_rest import (
150 exists,
151 gen_args,
152 get_subdevice_type,
153 open_session,
154 prepare_payload,
155 session_timeout,
156 update_changed_flag,
157 )
158
159
160 def prepare_argument_spec():
161 argument_spec = {
162 "vcenter_hostname": dict(
163 type="str",
164 required=True,
165 fallback=(env_fallback, ["VMWARE_HOST"]),
166 ),
167 "vcenter_username": dict(
168 type="str",
169 required=True,
170 fallback=(env_fallback, ["VMWARE_USER"]),
171 ),
172 "vcenter_password": dict(
173 type="str",
174 required=True,
175 no_log=True,
176 fallback=(env_fallback, ["VMWARE_PASSWORD"]),
177 ),
178 "vcenter_validate_certs": dict(
179 type="bool",
180 required=False,
181 default=True,
182 fallback=(env_fallback, ["VMWARE_VALIDATE_CERTS"]),
183 ),
184 "vcenter_rest_log_file": dict(
185 type="str",
186 required=False,
187 fallback=(env_fallback, ["VMWARE_REST_LOG_FILE"]),
188 ),
189 "session_timeout": dict(
190 type="float",
191 required=False,
192 fallback=(env_fallback, ["VMWARE_SESSION_TIMEOUT"]),
193 ),
194 }
195
196 argument_spec["delay"] = {"type": "int"}
197 argument_spec["reason"] = {"type": "str"}
198 argument_spec["state"] = {
199 "required": True,
200 "type": "str",
201 "choices": ["cancel", "poweroff", "reboot"],
202 }
203
204 return argument_spec
205
206
207 async def main():
208 required_if = list([])
209
210 module_args = prepare_argument_spec()
211 module = AnsibleModule(
212 argument_spec=module_args, required_if=required_if, supports_check_mode=False
213 )
214 if not module.params["vcenter_hostname"]:
215 module.fail_json("vcenter_hostname cannot be empty")
216 if not module.params["vcenter_username"]:
217 module.fail_json("vcenter_username cannot be empty")
218 if not module.params["vcenter_password"]:
219 module.fail_json("vcenter_password cannot be empty")
220 try:
221 session = await open_session(
222 vcenter_hostname=module.params["vcenter_hostname"],
223 vcenter_username=module.params["vcenter_username"],
224 vcenter_password=module.params["vcenter_password"],
225 validate_certs=module.params["vcenter_validate_certs"],
226 log_file=module.params["vcenter_rest_log_file"],
227 )
228 except Exception as err:
229 if hasattr(err, "get_message"):
230 module.fail_json(err.get_message())
231 else:
232 module.fail_json(str(err))
233 result = await entry_point(module, session)
234 module.exit_json(**result)
235
236
237 # template: default_module.j2
238 def build_url(params):
239 return ("https://{vcenter_hostname}" "/api/appliance/shutdown").format(**params)
240
241
242 async def entry_point(module, session):
243
244 if module.params["state"] == "present":
245 if "_create" in globals():
246 operation = "create"
247 else:
248 operation = "update"
249 elif module.params["state"] == "absent":
250 operation = "delete"
251 else:
252 operation = module.params["state"]
253
254 func = globals()["_" + operation]
255
256 return await func(module.params, session)
257
258
259 async def _cancel(params, session):
260 _in_query_parameters = PAYLOAD_FORMAT["cancel"]["query"].keys()
261 payload = prepare_payload(params, PAYLOAD_FORMAT["cancel"])
262 subdevice_type = get_subdevice_type("/api/appliance/shutdown?action=cancel")
263 if subdevice_type and not params[subdevice_type]:
264 _json = await exists(params, session, build_url(params))
265 if _json:
266 params[subdevice_type] = _json["id"]
267 _url = (
268 "https://{vcenter_hostname}"
269 # aa
270 "/api/appliance/shutdown?action=cancel"
271 ).format(**params) + gen_args(params, _in_query_parameters)
272 async with session.post(_url, json=payload, **session_timeout(params)) as resp:
273 try:
274 if resp.headers["Content-Type"] == "application/json":
275 _json = await resp.json()
276 except KeyError:
277 _json = {}
278 if "value" not in _json: # 7.0.2
279 _json = {"value": _json}
280
281 return await update_changed_flag(_json, resp.status, "cancel")
282
283
284 async def _poweroff(params, session):
285 _in_query_parameters = PAYLOAD_FORMAT["poweroff"]["query"].keys()
286 payload = prepare_payload(params, PAYLOAD_FORMAT["poweroff"])
287 subdevice_type = get_subdevice_type("/api/appliance/shutdown?action=poweroff")
288 if subdevice_type and not params[subdevice_type]:
289 _json = await exists(params, session, build_url(params))
290 if _json:
291 params[subdevice_type] = _json["id"]
292 _url = (
293 "https://{vcenter_hostname}"
294 # aa
295 "/api/appliance/shutdown?action=poweroff"
296 ).format(**params) + gen_args(params, _in_query_parameters)
297 async with session.post(_url, json=payload, **session_timeout(params)) as resp:
298 try:
299 if resp.headers["Content-Type"] == "application/json":
300 _json = await resp.json()
301 except KeyError:
302 _json = {}
303 if "value" not in _json: # 7.0.2
304 _json = {"value": _json}
305
306 return await update_changed_flag(_json, resp.status, "poweroff")
307
308
309 async def _reboot(params, session):
310 _in_query_parameters = PAYLOAD_FORMAT["reboot"]["query"].keys()
311 payload = prepare_payload(params, PAYLOAD_FORMAT["reboot"])
312 subdevice_type = get_subdevice_type("/api/appliance/shutdown?action=reboot")
313 if subdevice_type and not params[subdevice_type]:
314 _json = await exists(params, session, build_url(params))
315 if _json:
316 params[subdevice_type] = _json["id"]
317 _url = (
318 "https://{vcenter_hostname}"
319 # aa
320 "/api/appliance/shutdown?action=reboot"
321 ).format(**params) + gen_args(params, _in_query_parameters)
322 async with session.post(_url, json=payload, **session_timeout(params)) as resp:
323 try:
324 if resp.headers["Content-Type"] == "application/json":
325 _json = await resp.json()
326 except KeyError:
327 _json = {}
328 if "value" not in _json: # 7.0.2
329 _json = {"value": _json}
330
331 return await update_changed_flag(_json, resp.status, "reboot")
332
333
334 if __name__ == "__main__":
335 import asyncio
336
337 current_loop = asyncio.new_event_loop()
338 try:
339 asyncio.set_event_loop(current_loop)
340 current_loop.run_until_complete(main())
341 finally:
342 current_loop.close()