Debian Codegraph @

ansible_collections/vmware/vmware_rest/plugins/modules/appliance_services.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_services
12 short_description: Restarts a service
13 description: Restarts a service
14 options:
15 service:
16 description:
17 - identifier of the service to restart
18 - The parameter must be the id of a resource returned by M(vmware.vmware_rest.appliance_services_info).
19 This parameter is mandatory.
20 required: true
21 type: str
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 - restart
33 - start
34 - stop
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 author:
76 - Ansible Cloud Team (@ansible-collections)
77 version_added: 2.0.0
78 requirements:
79 - vSphere 7.0.3 or greater
80 - python >= 3.6
81 - aiohttp
82 notes:
83 - Tested on vSphere 7.0.3
84 """
85
86 EXAMPLES = r"""
87 - name: Stop the ntpd service
88 vmware.vmware_rest.appliance_services:
89 service: ntpd
90 state: stop
91 register: result
92
93 - name: Start the ntpd service
94 vmware.vmware_rest.appliance_services:
95 service: ntpd
96 state: start
97 register: result
98
99 - name: Restart the ntpd service
100 vmware.vmware_rest.appliance_services:
101 service: ntpd
102 state: restart
103 register: result
104 """
105 RETURN = r"""
106 # content generated by the update_return_section callback# task: Restart the ntpd service
107 value:
108 description: Restart the ntpd service
109 returned: On success
110 sample: {}
111 type: dict
112 """
113
114
115 # This structure describes the format of the data expected by the end-points
116 PAYLOAD_FORMAT = {
117 "stop": {"query": {}, "body": {}, "path": {"service": "service"}},
118 "start": {"query": {}, "body": {}, "path": {"service": "service"}},
119 "restart": {"query": {}, "body": {}, "path": {"service": "service"}},
120 } # pylint: disable=line-too-long
121
122 from ansible.module_utils.basic import env_fallback
123 import os
124
125 if os.getenv("VMWARE_ENABLE_TURBO", False):
126 try:
127 from ansible_collections.cloud.common.plugins.module_utils.turbo.module import (
128 AnsibleTurboModule as AnsibleModule,
129 )
130
131 AnsibleModule.collection_name = "vmware.vmware_rest"
132 except ImportError:
133 from ansible.module_utils.basic import AnsibleModule
134 else:
135 from ansible.module_utils.basic import AnsibleModule
136
137 from ansible_collections.vmware.vmware_rest.plugins.module_utils.vmware_rest import (
138 exists,
139 gen_args,
140 get_subdevice_type,
141 open_session,
142 prepare_payload,
143 session_timeout,
144 update_changed_flag,
145 )
146
147
148 def prepare_argument_spec():
149 argument_spec = {
150 "vcenter_hostname": dict(
151 type="str",
152 required=True,
153 fallback=(env_fallback, ["VMWARE_HOST"]),
154 ),
155 "vcenter_username": dict(
156 type="str",
157 required=True,
158 fallback=(env_fallback, ["VMWARE_USER"]),
159 ),
160 "vcenter_password": dict(
161 type="str",
162 required=True,
163 no_log=True,
164 fallback=(env_fallback, ["VMWARE_PASSWORD"]),
165 ),
166 "vcenter_validate_certs": dict(
167 type="bool",
168 required=False,
169 default=True,
170 fallback=(env_fallback, ["VMWARE_VALIDATE_CERTS"]),
171 ),
172 "vcenter_rest_log_file": dict(
173 type="str",
174 required=False,
175 fallback=(env_fallback, ["VMWARE_REST_LOG_FILE"]),
176 ),
177 "session_timeout": dict(
178 type="float",
179 required=False,
180 fallback=(env_fallback, ["VMWARE_SESSION_TIMEOUT"]),
181 ),
182 }
183
184 argument_spec["service"] = {"required": True, "type": "str"}
185 argument_spec["state"] = {
186 "required": True,
187 "type": "str",
188 "choices": ["restart", "start", "stop"],
189 }
190
191 return argument_spec
192
193
194 async def main():
195 required_if = list([])
196
197 module_args = prepare_argument_spec()
198 module = AnsibleModule(
199 argument_spec=module_args, required_if=required_if, supports_check_mode=False
200 )
201 if not module.params["vcenter_hostname"]:
202 module.fail_json("vcenter_hostname cannot be empty")
203 if not module.params["vcenter_username"]:
204 module.fail_json("vcenter_username cannot be empty")
205 if not module.params["vcenter_password"]:
206 module.fail_json("vcenter_password cannot be empty")
207 try:
208 session = await open_session(
209 vcenter_hostname=module.params["vcenter_hostname"],
210 vcenter_username=module.params["vcenter_username"],
211 vcenter_password=module.params["vcenter_password"],
212 validate_certs=module.params["vcenter_validate_certs"],
213 log_file=module.params["vcenter_rest_log_file"],
214 )
215 except Exception as err:
216 if hasattr(err, "get_message"):
217 module.fail_json(err.get_message())
218 else:
219 module.fail_json(str(err))
220 result = await entry_point(module, session)
221 module.exit_json(**result)
222
223
224 # template: default_module.j2
225 def build_url(params):
226 return ("https://{vcenter_hostname}" "/api/appliance/services").format(**params)
227
228
229 async def entry_point(module, session):
230
231 if module.params["state"] == "present":
232 if "_create" in globals():
233 operation = "create"
234 else:
235 operation = "update"
236 elif module.params["state"] == "absent":
237 operation = "delete"
238 else:
239 operation = module.params["state"]
240
241 func = globals()["_" + operation]
242
243 return await func(module.params, session)
244
245
246 async def _restart(params, session):
247 _in_query_parameters = PAYLOAD_FORMAT["restart"]["query"].keys()
248 payload = prepare_payload(params, PAYLOAD_FORMAT["restart"])
249 subdevice_type = get_subdevice_type(
250 "/api/appliance/services/{service}?action=restart"
251 )
252 if subdevice_type and not params[subdevice_type]:
253 _json = await exists(params, session, build_url(params))
254 if _json:
255 params[subdevice_type] = _json["id"]
256 _url = (
257 "https://{vcenter_hostname}"
258 # aa
259 "/api/appliance/services/{service}?action=restart"
260 ).format(**params) + gen_args(params, _in_query_parameters)
261 async with session.post(_url, json=payload, **session_timeout(params)) as resp:
262 try:
263 if resp.headers["Content-Type"] == "application/json":
264 _json = await resp.json()
265 except KeyError:
266 _json = {}
267 if "value" not in _json: # 7.0.2
268 _json = {"value": _json}
269
270 return await update_changed_flag(_json, resp.status, "restart")
271
272
273 async def _start(params, session):
274 _in_query_parameters = PAYLOAD_FORMAT["start"]["query"].keys()
275 payload = prepare_payload(params, PAYLOAD_FORMAT["start"])
276 subdevice_type = get_subdevice_type(
277 "/api/appliance/services/{service}?action=start"
278 )
279 if subdevice_type and not params[subdevice_type]:
280 _json = await exists(params, session, build_url(params))
281 if _json:
282 params[subdevice_type] = _json["id"]
283 _url = (
284 "https://{vcenter_hostname}"
285 # aa
286 "/api/appliance/services/{service}?action=start"
287 ).format(**params) + gen_args(params, _in_query_parameters)
288 async with session.post(_url, json=payload, **session_timeout(params)) as resp:
289 try:
290 if resp.headers["Content-Type"] == "application/json":
291 _json = await resp.json()
292 except KeyError:
293 _json = {}
294 if "value" not in _json: # 7.0.2
295 _json = {"value": _json}
296
297 return await update_changed_flag(_json, resp.status, "start")
298
299
300 async def _stop(params, session):
301 _in_query_parameters = PAYLOAD_FORMAT["stop"]["query"].keys()
302 payload = prepare_payload(params, PAYLOAD_FORMAT["stop"])
303 subdevice_type = get_subdevice_type("/api/appliance/services/{service}?action=stop")
304 if subdevice_type and not params[subdevice_type]:
305 _json = await exists(params, session, build_url(params))
306 if _json:
307 params[subdevice_type] = _json["id"]
308 _url = (
309 "https://{vcenter_hostname}"
310 # aa
311 "/api/appliance/services/{service}?action=stop"
312 ).format(**params) + gen_args(params, _in_query_parameters)
313 async with session.post(_url, json=payload, **session_timeout(params)) as resp:
314 try:
315 if resp.headers["Content-Type"] == "application/json":
316 _json = await resp.json()
317 except KeyError:
318 _json = {}
319 if "value" not in _json: # 7.0.2
320 _json = {"value": _json}
321
322 return await update_changed_flag(_json, resp.status, "stop")
323
324
325 if __name__ == "__main__":
326 import asyncio
327
328 current_loop = asyncio.new_event_loop()
329 try:
330 asyncio.set_event_loop(current_loop)
331 current_loop.run_until_complete(main())
332 finally:
333 current_loop.close()