Debian Codegraph @

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