Debian Codegraph @

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