Debian Codegraph @

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