Debian Codegraph @

ansible_collections/vmware/vmware_rest/plugins/modules/appliance_services_info.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_info
12 short_description: Returns the state of a service.
13 description: Returns the state of a service.
14 options:
15 service:
16 description:
17 - identifier of the service whose state is being queried.
18 - The parameter must be the id of a resource returned by M(vmware.vmware_rest.appliance_services_info).
19 Required with I(state=['get'])
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 vcenter_hostname:
30 description:
31 - The hostname or IP address of the vSphere vCenter
32 - If the value is not specified in the task, the value of environment variable
33 C(VMWARE_HOST) will be used instead.
34 required: true
35 type: str
36 vcenter_password:
37 description:
38 - The vSphere vCenter password
39 - If the value is not specified in the task, the value of environment variable
40 C(VMWARE_PASSWORD) will be used instead.
41 required: true
42 type: str
43 vcenter_rest_log_file:
44 description:
45 - 'You can use this optional parameter to set the location of a log file. '
46 - 'This file will be used to record the HTTP REST interaction. '
47 - 'The file will be stored on the host that runs the module. '
48 - 'If the value is not specified in the task, the value of '
49 - environment variable C(VMWARE_REST_LOG_FILE) will be used instead.
50 type: str
51 vcenter_username:
52 description:
53 - The vSphere vCenter username
54 - If the value is not specified in the task, the value of environment variable
55 C(VMWARE_USER) will be used instead.
56 required: true
57 type: str
58 vcenter_validate_certs:
59 default: true
60 description:
61 - Allows connection when SSL certificates are not valid. Set to C(false) when
62 certificates are not trusted.
63 - If the value is not specified in the task, the value of environment variable
64 C(VMWARE_VALIDATE_CERTS) will be used instead.
65 type: bool
66 author:
67 - Ansible Cloud Team (@ansible-collections)
68 version_added: 2.0.0
69 requirements:
70 - vSphere 7.0.3 or greater
71 - python >= 3.6
72 - aiohttp
73 notes:
74 - Tested on vSphere 7.0.3
75 """
76
77 EXAMPLES = r"""
78 - name: Get information about ntpd
79 vmware.vmware_rest.appliance_services_info:
80 service: ntpd
81 register: result
82 """
83 RETURN = r"""
84 # content generated by the update_return_section callback# task: Get information about ntpd
85 id:
86 description: moid of the resource
87 returned: On success
88 sample: ntpd
89 type: str
90 value:
91 description: Get information about ntpd
92 returned: On success
93 sample:
94 description: ntpd.service
95 state: STARTED
96 type: dict
97 """
98
99
100 # This structure describes the format of the data expected by the end-points
101 PAYLOAD_FORMAT = {
102 "get": {"query": {}, "body": {}, "path": {"service": "service"}},
103 "list": {"query": {}, "body": {}, "path": {}},
104 } # pylint: disable=line-too-long
105
106 from ansible.module_utils.basic import env_fallback
107 import os
108
109 if os.getenv("VMWARE_ENABLE_TURBO", False):
110 try:
111 from ansible_collections.cloud.common.plugins.module_utils.turbo.module import (
112 AnsibleTurboModule as AnsibleModule,
113 )
114
115 AnsibleModule.collection_name = "vmware.vmware_rest"
116 except ImportError:
117 from ansible.module_utils.basic import AnsibleModule
118 else:
119 from ansible.module_utils.basic import AnsibleModule
120
121 from ansible_collections.vmware.vmware_rest.plugins.module_utils.vmware_rest import (
122 build_full_device_list,
123 exists,
124 gen_args,
125 open_session,
126 session_timeout,
127 update_changed_flag,
128 )
129
130
131 def prepare_argument_spec():
132 argument_spec = {
133 "vcenter_hostname": dict(
134 type="str",
135 required=True,
136 fallback=(env_fallback, ["VMWARE_HOST"]),
137 ),
138 "vcenter_username": dict(
139 type="str",
140 required=True,
141 fallback=(env_fallback, ["VMWARE_USER"]),
142 ),
143 "vcenter_password": dict(
144 type="str",
145 required=True,
146 no_log=True,
147 fallback=(env_fallback, ["VMWARE_PASSWORD"]),
148 ),
149 "vcenter_validate_certs": dict(
150 type="bool",
151 required=False,
152 default=True,
153 fallback=(env_fallback, ["VMWARE_VALIDATE_CERTS"]),
154 ),
155 "vcenter_rest_log_file": dict(
156 type="str",
157 required=False,
158 fallback=(env_fallback, ["VMWARE_REST_LOG_FILE"]),
159 ),
160 "session_timeout": dict(
161 type="float",
162 required=False,
163 fallback=(env_fallback, ["VMWARE_SESSION_TIMEOUT"]),
164 ),
165 }
166
167 argument_spec["service"] = {"type": "str"}
168
169 return argument_spec
170
171
172 async def main():
173 required_if = list([])
174
175 module_args = prepare_argument_spec()
176 module = AnsibleModule(
177 argument_spec=module_args, required_if=required_if, supports_check_mode=True
178 )
179 if not module.params["vcenter_hostname"]:
180 module.fail_json("vcenter_hostname cannot be empty")
181 if not module.params["vcenter_username"]:
182 module.fail_json("vcenter_username cannot be empty")
183 if not module.params["vcenter_password"]:
184 module.fail_json("vcenter_password cannot be empty")
185 try:
186 session = await open_session(
187 vcenter_hostname=module.params["vcenter_hostname"],
188 vcenter_username=module.params["vcenter_username"],
189 vcenter_password=module.params["vcenter_password"],
190 validate_certs=module.params["vcenter_validate_certs"],
191 log_file=module.params["vcenter_rest_log_file"],
192 )
193 except Exception as err:
194 if hasattr(err, "get_message"):
195 module.fail_json(err.get_message())
196 else:
197 module.fail_json(str(err))
198 result = await entry_point(module, session)
199 module.exit_json(**result)
200
201
202 # template: info_list_and_get_module.j2
203 def build_url(params):
204 import yarl
205
206 if params.get("service"):
207 _in_query_parameters = PAYLOAD_FORMAT["get"]["query"].keys()
208 return yarl.URL(
209 ("https://{vcenter_hostname}" "/api/appliance/services/").format(**params)
210 + params["service"]
211 + gen_args(params, _in_query_parameters),
212 encoded=True,
213 )
214 _in_query_parameters = PAYLOAD_FORMAT["list"]["query"].keys()
215 return yarl.URL(
216 ("https://{vcenter_hostname}" "/api/appliance/services").format(**params)
217 + gen_args(params, _in_query_parameters),
218 encoded=True,
219 )
220
221
222 async def entry_point(module, session):
223 url = build_url(module.params)
224 async with session.get(url, **session_timeout(module.params)) as resp:
225 _json = await resp.json()
226
227 if "value" not in _json: # 7.0.2+
228 _json = {"value": _json}
229
230 if module.params.get("service"):
231 _json["id"] = module.params.get("service")
232 elif module.params.get("label"): # TODO extend the list of filter
233 _json = await exists(module.params, session, str(url))
234 elif (
235 isinstance(_json["value"], list)
236 and len(_json["value"]) > 0
237 and isinstance(_json["value"][0], str)
238 ):
239 # this is a list of id, we fetch the details
240 full_device_list = await build_full_device_list(session, str(url), _json)
241 _json = {"value": [i["value"] for i in full_device_list]}
242
243 return await update_changed_flag(_json, resp.status, "get")
244
245
246 if __name__ == "__main__":
247 import asyncio
248
249 current_loop = asyncio.new_event_loop()
250 try:
251 asyncio.set_event_loop(current_loop)
252 current_loop.run_until_complete(main())
253 finally:
254 current_loop.close()