Debian Codegraph @

ansible_collections/vmware/vmware_rest/plugins/modules/vcenter_host_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: vcenter_host_info
12 short_description: Returns information about at most 2500 visible (subject to permission
13 checks) hosts in vCenter matching the Host.FilterSpec.
14 description: Returns information about at most 2500 visible (subject to permission
15 checks) hosts in vCenter matching the Host.FilterSpec.
16 options:
17 clusters:
18 description:
19 - Clusters that must contain the hosts for the hosts to match the filter.
20 - If unset or empty, hosts in any cluster and hosts that are not in a cluster
21 match the filter. If this field is not empty and I(standalone) is true,
22 no hosts will match the filter.
23 - When clients pass a value of this structure as a parameter, the field must
24 contain the id of resources returned by M(vmware.vmware_rest.vcenter_cluster_info).
25 elements: str
26 type: list
27 connection_states:
28 description:
29 - Connection states that a host must be in to match the filter (see I()
30 - If unset or empty, hosts in any connection state match the filter.
31 elements: str
32 type: list
33 datacenters:
34 aliases:
35 - filter_datacenters
36 description:
37 - Datacenters that must contain the hosts for the hosts to match the filter.
38 - If unset or empty, hosts in any datacenter match the filter.
39 - When clients pass a value of this structure as a parameter, the field must
40 contain the id of resources returned by M(vmware.vmware_rest.vcenter_datacenter_info).
41 elements: str
42 type: list
43 folders:
44 aliases:
45 - filter_folders
46 description:
47 - Folders that must contain the hosts for the hosts to match the filter.
48 - If unset or empty, hosts in any folder match the filter.
49 - When clients pass a value of this structure as a parameter, the field must
50 contain the id of resources returned by M(vmware.vmware_rest.vcenter_folder_info).
51 elements: str
52 type: list
53 hosts:
54 description:
55 - Identifiers of hosts that can match the filter.
56 - If unset or empty, hosts with any identifier match the filter.
57 - When clients pass a value of this structure as a parameter, the field must
58 contain the id of resources returned by M(vmware.vmware_rest.vcenter_host_info).
59 elements: str
60 type: list
61 names:
62 aliases:
63 - filter_names
64 description:
65 - Names that hosts must have to match the filter (see I(name)).
66 - If unset or empty, hosts with any name match the filter.
67 elements: str
68 type: list
69 session_timeout:
70 description:
71 - 'Timeout settings for client session. '
72 - 'The maximal number of seconds for the whole operation including connection
73 establishment, request sending and response. '
74 - The default value is 300s.
75 type: float
76 version_added: 2.1.0
77 standalone:
78 description:
79 - If true, only hosts that are not part of a cluster can match the filter,
80 and if false, only hosts that are are part of a cluster can match the
81 filter.
82 - If unset Hosts can match filter independent of whether they are part of
83 a cluster or not. If this field is true and I(clusters) os not empty,
84 no hosts will match the filter.
85 type: bool
86 vcenter_hostname:
87 description:
88 - The hostname or IP address of the vSphere vCenter
89 - If the value is not specified in the task, the value of environment variable
90 C(VMWARE_HOST) will be used instead.
91 required: true
92 type: str
93 vcenter_password:
94 description:
95 - The vSphere vCenter password
96 - If the value is not specified in the task, the value of environment variable
97 C(VMWARE_PASSWORD) will be used instead.
98 required: true
99 type: str
100 vcenter_rest_log_file:
101 description:
102 - 'You can use this optional parameter to set the location of a log file. '
103 - 'This file will be used to record the HTTP REST interaction. '
104 - 'The file will be stored on the host that runs the module. '
105 - 'If the value is not specified in the task, the value of '
106 - environment variable C(VMWARE_REST_LOG_FILE) will be used instead.
107 type: str
108 vcenter_username:
109 description:
110 - The vSphere vCenter username
111 - If the value is not specified in the task, the value of environment variable
112 C(VMWARE_USER) will be used instead.
113 required: true
114 type: str
115 vcenter_validate_certs:
116 default: true
117 description:
118 - Allows connection when SSL certificates are not valid. Set to C(false) when
119 certificates are not trusted.
120 - If the value is not specified in the task, the value of environment variable
121 C(VMWARE_VALIDATE_CERTS) will be used instead.
122 type: bool
123 author:
124 - Ansible Cloud Team (@ansible-collections)
125 version_added: 0.1.0
126 requirements:
127 - vSphere 7.0.3 or greater
128 - python >= 3.6
129 - aiohttp
130 notes:
131 - Tested on vSphere 7.0.3
132 """
133
134 EXAMPLES = r"""
135 - name: Get a list of the hosts
136 vmware.vmware_rest.vcenter_host_info:
137 register: my_hosts
138 """
139 RETURN = r"""
140 # content generated by the update_return_section callback# task: Get a list of the hosts
141 value:
142 description: Get a list of the hosts
143 returned: On success
144 sample:
145 - connection_state: CONNECTED
146 host: host-1013
147 name: esxi1.test
148 power_state: POWERED_ON
149 type: list
150 """
151
152
153 # This structure describes the format of the data expected by the end-points
154 PAYLOAD_FORMAT = {
155 "list": {
156 "query": {
157 "clusters": "clusters",
158 "connection_states": "connection_states",
159 "datacenters": "datacenters",
160 "folders": "folders",
161 "hosts": "hosts",
162 "names": "names",
163 "standalone": "standalone",
164 },
165 "body": {},
166 "path": {},
167 }
168 } # pylint: disable=line-too-long
169
170 from ansible.module_utils.basic import env_fallback
171 import os
172
173 if os.getenv("VMWARE_ENABLE_TURBO", False):
174 try:
175 from ansible_collections.cloud.common.plugins.module_utils.turbo.module import (
176 AnsibleTurboModule as AnsibleModule,
177 )
178
179 AnsibleModule.collection_name = "vmware.vmware_rest"
180 except ImportError:
181 from ansible.module_utils.basic import AnsibleModule
182 else:
183 from ansible.module_utils.basic import AnsibleModule
184
185 from ansible_collections.vmware.vmware_rest.plugins.module_utils.vmware_rest import (
186 build_full_device_list,
187 exists,
188 gen_args,
189 open_session,
190 session_timeout,
191 update_changed_flag,
192 )
193
194
195 def prepare_argument_spec():
196 argument_spec = {
197 "vcenter_hostname": dict(
198 type="str",
199 required=True,
200 fallback=(env_fallback, ["VMWARE_HOST"]),
201 ),
202 "vcenter_username": dict(
203 type="str",
204 required=True,
205 fallback=(env_fallback, ["VMWARE_USER"]),
206 ),
207 "vcenter_password": dict(
208 type="str",
209 required=True,
210 no_log=True,
211 fallback=(env_fallback, ["VMWARE_PASSWORD"]),
212 ),
213 "vcenter_validate_certs": dict(
214 type="bool",
215 required=False,
216 default=True,
217 fallback=(env_fallback, ["VMWARE_VALIDATE_CERTS"]),
218 ),
219 "vcenter_rest_log_file": dict(
220 type="str",
221 required=False,
222 fallback=(env_fallback, ["VMWARE_REST_LOG_FILE"]),
223 ),
224 "session_timeout": dict(
225 type="float",
226 required=False,
227 fallback=(env_fallback, ["VMWARE_SESSION_TIMEOUT"]),
228 ),
229 }
230
231 argument_spec["clusters"] = {"type": "list", "elements": "str"}
232 argument_spec["connection_states"] = {"type": "list", "elements": "str"}
233 argument_spec["datacenters"] = {
234 "aliases": ["filter_datacenters"],
235 "type": "list",
236 "elements": "str",
237 }
238 argument_spec["folders"] = {
239 "aliases": ["filter_folders"],
240 "type": "list",
241 "elements": "str",
242 }
243 argument_spec["hosts"] = {"type": "list", "elements": "str"}
244 argument_spec["names"] = {
245 "aliases": ["filter_names"],
246 "type": "list",
247 "elements": "str",
248 }
249 argument_spec["standalone"] = {"type": "bool"}
250
251 return argument_spec
252
253
254 async def main():
255 required_if = list([])
256
257 module_args = prepare_argument_spec()
258 module = AnsibleModule(
259 argument_spec=module_args, required_if=required_if, supports_check_mode=True
260 )
261 if not module.params["vcenter_hostname"]:
262 module.fail_json("vcenter_hostname cannot be empty")
263 if not module.params["vcenter_username"]:
264 module.fail_json("vcenter_username cannot be empty")
265 if not module.params["vcenter_password"]:
266 module.fail_json("vcenter_password cannot be empty")
267 try:
268 session = await open_session(
269 vcenter_hostname=module.params["vcenter_hostname"],
270 vcenter_username=module.params["vcenter_username"],
271 vcenter_password=module.params["vcenter_password"],
272 validate_certs=module.params["vcenter_validate_certs"],
273 log_file=module.params["vcenter_rest_log_file"],
274 )
275 except Exception as err:
276 if hasattr(err, "get_message"):
277 module.fail_json(err.get_message())
278 else:
279 module.fail_json(str(err))
280 result = await entry_point(module, session)
281 module.exit_json(**result)
282
283
284 # template: info_list_and_get_module.j2
285 def build_url(params):
286 import yarl
287
288 if params.get("host"):
289 _in_query_parameters = PAYLOAD_FORMAT["get"]["query"].keys()
290 return yarl.URL(
291 ("https://{vcenter_hostname}" "/api/vcenter/host/").format(**params)
292 + params["host"]
293 + gen_args(params, _in_query_parameters),
294 encoded=True,
295 )
296 _in_query_parameters = PAYLOAD_FORMAT["list"]["query"].keys()
297 return yarl.URL(
298 ("https://{vcenter_hostname}" "/api/vcenter/host").format(**params)
299 + gen_args(params, _in_query_parameters),
300 encoded=True,
301 )
302
303
304 async def entry_point(module, session):
305 url = build_url(module.params)
306 async with session.get(url, **session_timeout(module.params)) as resp:
307 _json = await resp.json()
308
309 if "value" not in _json: # 7.0.2+
310 _json = {"value": _json}
311
312 if module.params.get("host"):
313 _json["id"] = module.params.get("host")
314 elif module.params.get("label"): # TODO extend the list of filter
315 _json = await exists(module.params, session, str(url))
316 elif (
317 isinstance(_json["value"], list)
318 and len(_json["value"]) > 0
319 and isinstance(_json["value"][0], str)
320 ):
321 # this is a list of id, we fetch the details
322 full_device_list = await build_full_device_list(session, str(url), _json)
323 _json = {"value": [i["value"] for i in full_device_list]}
324
325 return await update_changed_flag(_json, resp.status, "get")
326
327
328 if __name__ == "__main__":
329 import asyncio
330
331 current_loop = asyncio.new_event_loop()
332 try:
333 asyncio.set_event_loop(current_loop)
334 current_loop.run_until_complete(main())
335 finally:
336 current_loop.close()