Debian Codegraph @

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