Debian Codegraph @

ansible_collections/vmware/vmware_rest/plugins/modules/appliance_vmon_service.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_vmon_service
12 short_description: Lists details of services managed by vMon.
13 description: Lists details of services managed by vMon.
14 options:
15 service:
16 description:
17 - identifier of the service whose properties are being updated.
18 - The parameter must be the id of a resource returned by M(vmware.vmware_rest.appliance_vmon_service).
19 Required with I(state=['restart', 'start', 'stop'])
20 type: str
21 session_timeout:
22 description:
23 - 'Timeout settings for client session. '
24 - 'The maximal number of seconds for the whole operation including connection
25 establishment, request sending and response. '
26 - The default value is 300s.
27 type: float
28 version_added: 2.1.0
29 startup_type:
30 choices:
31 - AUTOMATIC
32 - DISABLED
33 - MANUAL
34 description:
35 - The I(startup_type) enumerated type defines valid Startup Type for services
36 managed by vMon.
37 type: str
38 state:
39 choices:
40 - list_details
41 - present
42 - restart
43 - start
44 - stop
45 default: present
46 description: []
47 type: str
48 vcenter_hostname:
49 description:
50 - The hostname or IP address of the vSphere vCenter
51 - If the value is not specified in the task, the value of environment variable
52 C(VMWARE_HOST) will be used instead.
53 required: true
54 type: str
55 vcenter_password:
56 description:
57 - The vSphere vCenter password
58 - If the value is not specified in the task, the value of environment variable
59 C(VMWARE_PASSWORD) will be used instead.
60 required: true
61 type: str
62 vcenter_rest_log_file:
63 description:
64 - 'You can use this optional parameter to set the location of a log file. '
65 - 'This file will be used to record the HTTP REST interaction. '
66 - 'The file will be stored on the host that runs the module. '
67 - 'If the value is not specified in the task, the value of '
68 - environment variable C(VMWARE_REST_LOG_FILE) will be used instead.
69 type: str
70 vcenter_username:
71 description:
72 - The vSphere vCenter username
73 - If the value is not specified in the task, the value of environment variable
74 C(VMWARE_USER) will be used instead.
75 required: true
76 type: str
77 vcenter_validate_certs:
78 default: true
79 description:
80 - Allows connection when SSL certificates are not valid. Set to C(false) when
81 certificates are not trusted.
82 - If the value is not specified in the task, the value of environment variable
83 C(VMWARE_VALIDATE_CERTS) will be used instead.
84 type: bool
85 author:
86 - Ansible Cloud Team (@ansible-collections)
87 version_added: 2.0.0
88 requirements:
89 - vSphere 7.0.3 or greater
90 - python >= 3.6
91 - aiohttp
92 notes:
93 - Tested on vSphere 7.0.3
94 """
95
96 EXAMPLES = r"""
97 - name: Adjust vpxd configuration
98 vmware.vmware_rest.appliance_vmon_service:
99 service: vpxd
100 startup_type: AUTOMATIC
101 register: result
102 """
103 RETURN = r"""
104 # content generated by the update_return_section callback# task: Adjust vpxd configuration
105 id:
106 description: moid of the resource
107 returned: On success
108 sample: vpxd
109 type: str
110 value:
111 description: Adjust vpxd configuration
112 returned: On success
113 sample: {}
114 type: dict
115 """
116
117
118 # This structure describes the format of the data expected by the end-points
119 PAYLOAD_FORMAT = {
120 "stop": {"query": {}, "body": {}, "path": {"service": "service"}},
121 "list_details": {"query": {}, "body": {}, "path": {}},
122 "restart": {"query": {}, "body": {}, "path": {"service": "service"}},
123 "update": {
124 "query": {},
125 "body": {"startup_type": "spec/startup_type"},
126 "path": {"service": "service"},
127 },
128 "start": {"query": {}, "body": {}, "path": {"service": "service"}},
129 } # pylint: disable=line-too-long
130
131 from ansible.module_utils.basic import env_fallback
132 import os
133
134 if os.getenv("VMWARE_ENABLE_TURBO", False):
135 try:
136 from ansible_collections.cloud.common.plugins.module_utils.turbo.module import (
137 AnsibleTurboModule as AnsibleModule,
138 )
139
140 AnsibleModule.collection_name = "vmware.vmware_rest"
141 except ImportError:
142 from ansible.module_utils.basic import AnsibleModule
143 else:
144 from ansible.module_utils.basic import AnsibleModule
145
146 from ansible_collections.vmware.vmware_rest.plugins.module_utils.vmware_rest import (
147 exists,
148 gen_args,
149 get_subdevice_type,
150 open_session,
151 prepare_payload,
152 session_timeout,
153 update_changed_flag,
154 )
155
156
157 def prepare_argument_spec():
158 argument_spec = {
159 "vcenter_hostname": dict(
160 type="str",
161 required=True,
162 fallback=(env_fallback, ["VMWARE_HOST"]),
163 ),
164 "vcenter_username": dict(
165 type="str",
166 required=True,
167 fallback=(env_fallback, ["VMWARE_USER"]),
168 ),
169 "vcenter_password": dict(
170 type="str",
171 required=True,
172 no_log=True,
173 fallback=(env_fallback, ["VMWARE_PASSWORD"]),
174 ),
175 "vcenter_validate_certs": dict(
176 type="bool",
177 required=False,
178 default=True,
179 fallback=(env_fallback, ["VMWARE_VALIDATE_CERTS"]),
180 ),
181 "vcenter_rest_log_file": dict(
182 type="str",
183 required=False,
184 fallback=(env_fallback, ["VMWARE_REST_LOG_FILE"]),
185 ),
186 "session_timeout": dict(
187 type="float",
188 required=False,
189 fallback=(env_fallback, ["VMWARE_SESSION_TIMEOUT"]),
190 ),
191 }
192
193 argument_spec["service"] = {"type": "str"}
194 argument_spec["startup_type"] = {
195 "type": "str",
196 "choices": ["AUTOMATIC", "DISABLED", "MANUAL"],
197 }
198 argument_spec["state"] = {
199 "type": "str",
200 "choices": ["list_details", "present", "restart", "start", "stop"],
201 "default": "present",
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}" "/rest/appliance/vmon/service").format(
240 **params
241 )
242
243
244 async def entry_point(module, session):
245
246 if module.params["state"] == "present":
247 if "_create" in globals():
248 operation = "create"
249 else:
250 operation = "update"
251 elif module.params["state"] == "absent":
252 operation = "delete"
253 else:
254 operation = module.params["state"]
255
256 func = globals()["_" + operation]
257
258 return await func(module.params, session)
259
260
261 async def _list_details(params, session):
262 _in_query_parameters = PAYLOAD_FORMAT["list_details"]["query"].keys()
263 payload = prepare_payload(params, PAYLOAD_FORMAT["list_details"])
264 subdevice_type = get_subdevice_type("/rest/appliance/vmon/service")
265 if subdevice_type and not params[subdevice_type]:
266 _json = await exists(params, session, build_url(params))
267 if _json:
268 params[subdevice_type] = _json["id"]
269 _url = (
270 "https://{vcenter_hostname}"
271 # aa
272 "/rest/appliance/vmon/service"
273 ).format(**params) + gen_args(params, _in_query_parameters)
274 async with session.get(_url, json=payload, **session_timeout(params)) as resp:
275 try:
276 if resp.headers["Content-Type"] == "application/json":
277 _json = await resp.json()
278 except KeyError:
279 _json = {}
280 if "value" not in _json: # 7.0.2
281 _json = {"value": _json}
282
283 return await update_changed_flag(_json, resp.status, "list_details")
284
285
286 async def _restart(params, session):
287 _in_query_parameters = PAYLOAD_FORMAT["restart"]["query"].keys()
288 payload = prepare_payload(params, PAYLOAD_FORMAT["restart"])
289 subdevice_type = get_subdevice_type(
290 "/rest/appliance/vmon/service/{service}/restart"
291 )
292 if subdevice_type and not params[subdevice_type]:
293 _json = await exists(params, session, build_url(params))
294 if _json:
295 params[subdevice_type] = _json["id"]
296 _url = (
297 "https://{vcenter_hostname}"
298 # aa
299 "/rest/appliance/vmon/service/{service}/restart"
300 ).format(**params) + gen_args(params, _in_query_parameters)
301 async with session.post(_url, json=payload, **session_timeout(params)) as resp:
302 try:
303 if resp.headers["Content-Type"] == "application/json":
304 _json = await resp.json()
305 except KeyError:
306 _json = {}
307 if "value" not in _json: # 7.0.2
308 _json = {"value": _json}
309
310 return await update_changed_flag(_json, resp.status, "restart")
311
312
313 async def _start(params, session):
314 _in_query_parameters = PAYLOAD_FORMAT["start"]["query"].keys()
315 payload = prepare_payload(params, PAYLOAD_FORMAT["start"])
316 subdevice_type = get_subdevice_type("/rest/appliance/vmon/service/{service}/start")
317 if subdevice_type and not params[subdevice_type]:
318 _json = await exists(params, session, build_url(params))
319 if _json:
320 params[subdevice_type] = _json["id"]
321 _url = (
322 "https://{vcenter_hostname}"
323 # aa
324 "/rest/appliance/vmon/service/{service}/start"
325 ).format(**params) + gen_args(params, _in_query_parameters)
326 async with session.post(_url, json=payload, **session_timeout(params)) as resp:
327 try:
328 if resp.headers["Content-Type"] == "application/json":
329 _json = await resp.json()
330 except KeyError:
331 _json = {}
332 if "value" not in _json: # 7.0.2
333 _json = {"value": _json}
334
335 return await update_changed_flag(_json, resp.status, "start")
336
337
338 async def _stop(params, session):
339 _in_query_parameters = PAYLOAD_FORMAT["stop"]["query"].keys()
340 payload = prepare_payload(params, PAYLOAD_FORMAT["stop"])
341 subdevice_type = get_subdevice_type("/rest/appliance/vmon/service/{service}/stop")
342 if subdevice_type and not params[subdevice_type]:
343 _json = await exists(params, session, build_url(params))
344 if _json:
345 params[subdevice_type] = _json["id"]
346 _url = (
347 "https://{vcenter_hostname}"
348 # aa
349 "/rest/appliance/vmon/service/{service}/stop"
350 ).format(**params) + gen_args(params, _in_query_parameters)
351 async with session.post(_url, json=payload, **session_timeout(params)) as resp:
352 try:
353 if resp.headers["Content-Type"] == "application/json":
354 _json = await resp.json()
355 except KeyError:
356 _json = {}
357 if "value" not in _json: # 7.0.2
358 _json = {"value": _json}
359
360 return await update_changed_flag(_json, resp.status, "stop")
361
362
363 async def _update(params, session):
364 payload = prepare_payload(params, PAYLOAD_FORMAT["update"])
365 _url = (
366 "https://{vcenter_hostname}" "/rest/appliance/vmon/service/{service}"
367 ).format(**params)
368 async with session.get(_url, **session_timeout(params)) as resp:
369 _json = await resp.json()
370 if "value" in _json:
371 value = _json["value"]
372 else: # 7.0.2 and greater
373 value = _json
374 for k, v in value.items():
375 if k in payload:
376 if isinstance(payload[k], dict) and isinstance(v, dict):
377 to_delete = True
378 for _k in list(payload[k].keys()):
379 if payload[k][_k] != v.get(_k):
380 to_delete = False
381 if to_delete:
382 del payload[k]
383 elif payload[k] == v:
384 del payload[k]
385 elif payload[k] == {}:
386 del payload[k]
387
388 if payload == {} or payload == {"spec": {}}:
389 # Nothing has changed
390 if "value" not in _json: # 7.0.2
391 _json = {"value": _json}
392 _json["id"] = params.get("service")
393 return await update_changed_flag(_json, resp.status, "get")
394 async with session.patch(_url, json=payload, **session_timeout(params)) as resp:
395 try:
396 if resp.headers["Content-Type"] == "application/json":
397 _json = await resp.json()
398 except KeyError:
399 _json = {}
400 if "value" not in _json: # 7.0.2
401 _json = {"value": _json}
402
403 # e.g: content_configuration
404 if not _json and resp.status == 204:
405 async with session.get(_url, **session_timeout(params)) as resp_get:
406 _json_get = await resp_get.json()
407 if _json_get:
408 _json = _json_get
409
410 _json["id"] = params.get("service")
411 return await update_changed_flag(_json, resp.status, "update")
412
413
414 if __name__ == "__main__":
415 import asyncio
416
417 current_loop = asyncio.new_event_loop()
418 try:
419 asyncio.set_event_loop(current_loop)
420 current_loop.run_until_complete(main())
421 finally:
422 current_loop.close()