Debian Codegraph @

ansible_collections/vmware/vmware_rest/plugins/modules/vcenter_resourcepool.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
12 short_description: Creates a resource pool.
13 description: Creates a resource pool.
14 options:
15 cpu_allocation:
16 description:
17 - Resource allocation for CPU.
18 - if unset or empty, the CPU allocation of the resource pool will not be changed.
19 - 'Valid attributes are:'
20 - ' - C(reservation) (int): Amount of resource that is guaranteed available
21 to a resource pool. Reserved resources are not wasted if they are not
22 used. If the utilization is less than the reservation, the resources can
23 be utilized by other running virtual machines. Units are MB fo memory,
24 and MHz for CPU.'
25 - If unset or empty, I(reservation) will be set to 0. (['present'])
26 - ' - C(expandable_reservation) (bool): In a resource pool with an expandable
27 reservation, the reservation can grow beyond the specified value, if the
28 parent resource pool has unreserved resources. A non-expandable reservation
29 is called a fixed reservation.'
30 - If unset or empty, I(expandable_reservation) will be set to true. (['present'])
31 - ' - C(limit) (int): The utilization of a resource pool will not exceed this
32 limit, even if there are available resources. This is typically used to
33 ensure a consistent performance of resource pools independent of available
34 resources. If set to -1, then there is no fixed limit on resource usage
35 (only bounded by available resources and shares). Units are MB for memory,
36 and MHz for CPU.'
37 - If unset or empty, I(limit) will be set to -1. (['present'])
38 - ' - C(shares) (dict): Shares are used in case of resource contention. ([''present''])'
39 - ' - Accepted keys:'
40 - ' - level (string): This option defines the possible values for the
41 allocation level.'
42 - 'Accepted value for this field:'
43 - ' - C(CUSTOM)'
44 - ' - C(HIGH)'
45 - ' - C(LOW)'
46 - ' - C(NORMAL)'
47 - ' - shares (integer): When I(level) is set to CUSTOM, it is the number
48 of shares allocated. Otherwise, this value is ignored. '
49 - ' There is no unit for this value. It is a relative measure based on the
50 settings for other resource pools.'
51 - ''
52 - This field is optional and it is only relevant when the value of I(level)
53 is CUSTOM.
54 type: dict
55 memory_allocation:
56 description:
57 - Resource allocation for CPU.
58 - if unset or empty, the CPU allocation of the resource pool will not be changed.
59 - 'Valid attributes are:'
60 - ' - C(reservation) (int): Amount of resource that is guaranteed available
61 to a resource pool. Reserved resources are not wasted if they are not
62 used. If the utilization is less than the reservation, the resources can
63 be utilized by other running virtual machines. Units are MB fo memory,
64 and MHz for CPU.'
65 - If unset or empty, I(reservation) will be set to 0. (['present'])
66 - ' - C(expandable_reservation) (bool): In a resource pool with an expandable
67 reservation, the reservation can grow beyond the specified value, if the
68 parent resource pool has unreserved resources. A non-expandable reservation
69 is called a fixed reservation.'
70 - If unset or empty, I(expandable_reservation) will be set to true. (['present'])
71 - ' - C(limit) (int): The utilization of a resource pool will not exceed this
72 limit, even if there are available resources. This is typically used to
73 ensure a consistent performance of resource pools independent of available
74 resources. If set to -1, then there is no fixed limit on resource usage
75 (only bounded by available resources and shares). Units are MB for memory,
76 and MHz for CPU.'
77 - If unset or empty, I(limit) will be set to -1. (['present'])
78 - ' - C(shares) (dict): Shares are used in case of resource contention. ([''present''])'
79 - ' - Accepted keys:'
80 - ' - level (string): This option defines the possible values for the
81 allocation level.'
82 - 'Accepted value for this field:'
83 - ' - C(CUSTOM)'
84 - ' - C(HIGH)'
85 - ' - C(LOW)'
86 - ' - C(NORMAL)'
87 - ' - shares (integer): When I(level) is set to CUSTOM, it is the number
88 of shares allocated. Otherwise, this value is ignored. '
89 - ' There is no unit for this value. It is a relative measure based on the
90 settings for other resource pools.'
91 - ''
92 - This field is optional and it is only relevant when the value of I(level)
93 is CUSTOM.
94 type: dict
95 name:
96 description:
97 - Name of the resource pool.
98 - if unset or empty, the name of the resource pool will not be changed. Required
99 with I(state=['present'])
100 type: str
101 parent:
102 description:
103 - Parent of the created resource pool.
104 - When clients pass a value of this structure as a parameter, the field must
105 be the id of a resource returned by M(vmware.vmware_rest.vcenter_resourcepool_info).
106 Required with I(state=['present'])
107 type: str
108 resource_pool:
109 description:
110 - Identifier of the resource pool to be deleted.
111 - The parameter must be the id of a resource returned by M(vmware.vmware_rest.vcenter_resourcepool_info).
112 Required with I(state=['absent', 'present'])
113 type: str
114 session_timeout:
115 description:
116 - 'Timeout settings for client session. '
117 - 'The maximal number of seconds for the whole operation including connection
118 establishment, request sending and response. '
119 - The default value is 300s.
120 type: float
121 version_added: 2.1.0
122 state:
123 choices:
124 - absent
125 - present
126 default: present
127 description: []
128 type: str
129 vcenter_hostname:
130 description:
131 - The hostname or IP address of the vSphere vCenter
132 - If the value is not specified in the task, the value of environment variable
133 C(VMWARE_HOST) will be used instead.
134 required: true
135 type: str
136 vcenter_password:
137 description:
138 - The vSphere vCenter password
139 - If the value is not specified in the task, the value of environment variable
140 C(VMWARE_PASSWORD) will be used instead.
141 required: true
142 type: str
143 vcenter_rest_log_file:
144 description:
145 - 'You can use this optional parameter to set the location of a log file. '
146 - 'This file will be used to record the HTTP REST interaction. '
147 - 'The file will be stored on the host that runs the module. '
148 - 'If the value is not specified in the task, the value of '
149 - environment variable C(VMWARE_REST_LOG_FILE) will be used instead.
150 type: str
151 vcenter_username:
152 description:
153 - The vSphere vCenter username
154 - If the value is not specified in the task, the value of environment variable
155 C(VMWARE_USER) will be used instead.
156 required: true
157 type: str
158 vcenter_validate_certs:
159 default: true
160 description:
161 - Allows connection when SSL certificates are not valid. Set to C(false) when
162 certificates are not trusted.
163 - If the value is not specified in the task, the value of environment variable
164 C(VMWARE_VALIDATE_CERTS) will be used instead.
165 type: bool
166 author:
167 - Ansible Cloud Team (@ansible-collections)
168 version_added: 0.3.0
169 requirements:
170 - vSphere 7.0.3 or greater
171 - python >= 3.6
172 - aiohttp
173 notes:
174 - Tested on vSphere 7.0.3
175 """
176
177 EXAMPLES = r"""
178 - name: Get the existing resource pools
179 vmware.vmware_rest.vcenter_resourcepool_info:
180 register: resource_pools
181 - name: Create an Ad hoc resource pool
182 vmware.vmware_rest.vcenter_resourcepool:
183 name: my_resource_pool
184 parent: '{{ resource_pools.value[0].resource_pool }}'
185 cpu_allocation:
186 expandable_reservation: true
187 limit: 40
188 reservation: 0
189 shares:
190 level: NORMAL
191 memory_allocation:
192 expandable_reservation: false
193 limit: 2000
194 reservation: 0
195 shares:
196 level: NORMAL
197 register: my_resource_pool
198 - name: Remove a resource pool
199 vmware.vmware_rest.vcenter_resourcepool:
200 resource_pool: '{{ my_resource_pool.id }}'
201 state: absent
202 - name: Create a generic resource pool
203 vmware.vmware_rest.vcenter_resourcepool:
204 name: my_resource_pool
205 parent: '{{ resource_pools.value[0].resource_pool }}'
206 register: my_resource_pool
207 - name: Modify a resource pool
208 vmware.vmware_rest.vcenter_resourcepool:
209 resource_pool: '{{ my_resource_pool.id }}'
210 cpu_allocation:
211 expandable_reservation: true
212 limit: -1
213 reservation: 0
214 shares:
215 level: NORMAL
216 memory_allocation:
217 expandable_reservation: false
218 limit: 1000
219 reservation: 0
220 shares:
221 level: NORMAL
222 """
223 RETURN = r"""
224 # content generated by the update_return_section callback# task: Create a generic resource pool
225 id:
226 description: moid of the resource
227 returned: On success
228 sample: resgroup-1009
229 type: str
230 value:
231 description: Create a generic resource pool
232 returned: On success
233 sample:
234 cpu_allocation:
235 expandable_reservation: 1
236 limit: -1
237 reservation: 0
238 shares:
239 level: NORMAL
240 memory_allocation:
241 expandable_reservation: 1
242 limit: -1
243 reservation: 0
244 shares:
245 level: NORMAL
246 name: my_resource_pool
247 resource_pools: []
248 type: dict
249 """
250
251
252 # This structure describes the format of the data expected by the end-points
253 PAYLOAD_FORMAT = {
254 "delete": {"query": {}, "body": {}, "path": {"resource_pool": "resource_pool"}},
255 "update": {
256 "query": {},
257 "body": {
258 "cpu_allocation": "cpu_allocation",
259 "memory_allocation": "memory_allocation",
260 "name": "name",
261 },
262 "path": {"resource_pool": "resource_pool"},
263 },
264 "create": {
265 "query": {},
266 "body": {
267 "cpu_allocation": "cpu_allocation",
268 "memory_allocation": "memory_allocation",
269 "name": "name",
270 "parent": "parent",
271 },
272 "path": {},
273 },
274 } # pylint: disable=line-too-long
275
276 from ansible.module_utils.basic import env_fallback
277 import os
278
279 if os.getenv("VMWARE_ENABLE_TURBO", False):
280 try:
281 from ansible_collections.cloud.common.plugins.module_utils.turbo.module import (
282 AnsibleTurboModule as AnsibleModule,
283 )
284
285 AnsibleModule.collection_name = "vmware.vmware_rest"
286 except ImportError:
287 from ansible.module_utils.basic import AnsibleModule
288 else:
289 from ansible.module_utils.basic import AnsibleModule
290
291 from ansible_collections.vmware.vmware_rest.plugins.module_utils.vmware_rest import (
292 exists,
293 gen_args,
294 get_device_info,
295 get_subdevice_type,
296 open_session,
297 prepare_payload,
298 session_timeout,
299 update_changed_flag,
300 )
301
302
303 def prepare_argument_spec():
304 argument_spec = {
305 "vcenter_hostname": dict(
306 type="str",
307 required=True,
308 fallback=(env_fallback, ["VMWARE_HOST"]),
309 ),
310 "vcenter_username": dict(
311 type="str",
312 required=True,
313 fallback=(env_fallback, ["VMWARE_USER"]),
314 ),
315 "vcenter_password": dict(
316 type="str",
317 required=True,
318 no_log=True,
319 fallback=(env_fallback, ["VMWARE_PASSWORD"]),
320 ),
321 "vcenter_validate_certs": dict(
322 type="bool",
323 required=False,
324 default=True,
325 fallback=(env_fallback, ["VMWARE_VALIDATE_CERTS"]),
326 ),
327 "vcenter_rest_log_file": dict(
328 type="str",
329 required=False,
330 fallback=(env_fallback, ["VMWARE_REST_LOG_FILE"]),
331 ),
332 "session_timeout": dict(
333 type="float",
334 required=False,
335 fallback=(env_fallback, ["VMWARE_SESSION_TIMEOUT"]),
336 ),
337 }
338
339 argument_spec["cpu_allocation"] = {"type": "dict"}
340 argument_spec["memory_allocation"] = {"type": "dict"}
341 argument_spec["name"] = {"type": "str"}
342 argument_spec["parent"] = {"type": "str"}
343 argument_spec["resource_pool"] = {"type": "str"}
344 argument_spec["state"] = {
345 "type": "str",
346 "choices": ["absent", "present"],
347 "default": "present",
348 }
349
350 return argument_spec
351
352
353 async def main():
354 required_if = list([])
355
356 module_args = prepare_argument_spec()
357 module = AnsibleModule(
358 argument_spec=module_args, required_if=required_if, supports_check_mode=False
359 )
360 if not module.params["vcenter_hostname"]:
361 module.fail_json("vcenter_hostname cannot be empty")
362 if not module.params["vcenter_username"]:
363 module.fail_json("vcenter_username cannot be empty")
364 if not module.params["vcenter_password"]:
365 module.fail_json("vcenter_password cannot be empty")
366 try:
367 session = await open_session(
368 vcenter_hostname=module.params["vcenter_hostname"],
369 vcenter_username=module.params["vcenter_username"],
370 vcenter_password=module.params["vcenter_password"],
371 validate_certs=module.params["vcenter_validate_certs"],
372 log_file=module.params["vcenter_rest_log_file"],
373 )
374 except Exception as err:
375 if hasattr(err, "get_message"):
376 module.fail_json(err.get_message())
377 else:
378 module.fail_json(str(err))
379 result = await entry_point(module, session)
380 module.exit_json(**result)
381
382
383 # template: default_module.j2
384 def build_url(params):
385 return ("https://{vcenter_hostname}" "/api/vcenter/resource-pool").format(**params)
386
387
388 async def entry_point(module, session):
389
390 if module.params["state"] == "present":
391 if "_create" in globals():
392 operation = "create"
393 else:
394 operation = "update"
395 elif module.params["state"] == "absent":
396 operation = "delete"
397 else:
398 operation = module.params["state"]
399
400 func = globals()["_" + operation]
401
402 return await func(module.params, session)
403
404
405 async def _create(params, session):
406
407 lookup_url = per_id_url = build_url(params)
408 uniquity_keys = ["resource_pool"]
409 comp_func = None
410
411 async def lookup_with_filters(params, session, url):
412 search_filter = ""
413
414 if "name" not in params:
415 return
416 async with session.get(f"{url}?names={params['name']}{search_filter}") as resp:
417 _json = await resp.json()
418 if isinstance(_json, list) and len(_json) == 1:
419 return await get_device_info(session, url, _json[0]["resource_pool"])
420
421 _json = None
422
423 if params["resource_pool"]:
424 _json = await get_device_info(
425 session, build_url(params), params["resource_pool"]
426 )
427
428 if not _json and (uniquity_keys or comp_func):
429 _json = await exists(
430 params,
431 session,
432 url=lookup_url,
433 uniquity_keys=uniquity_keys,
434 per_id_url=per_id_url,
435 comp_func=comp_func,
436 )
437
438 if not _json:
439 _json = await lookup_with_filters(params, session, build_url(params))
440
441 if _json:
442 if "value" not in _json: # 7.0.2+
443 _json = {"value": _json}
444 if "_update" in globals():
445 params["resource_pool"] = _json["id"]
446 return await globals()["_update"](params, session)
447
448 return await update_changed_flag(_json, 200, "get")
449
450 payload = prepare_payload(params, PAYLOAD_FORMAT["create"])
451 _url = ("https://{vcenter_hostname}" "/api/vcenter/resource-pool").format(**params)
452 async with session.post(_url, json=payload, **session_timeout(params)) as resp:
453 if resp.status == 500:
454 text = await resp.text()
455 raise Exception(f"Request has failed: status={resp.status}, {text}")
456 try:
457 if resp.headers["Content-Type"] == "application/json":
458 _json = await resp.json()
459 except KeyError:
460 _json = {}
461
462 if (resp.status in [200, 201]) and "error" not in _json:
463 if isinstance(_json, str): # 7.0.2 and greater
464 _id = _json # TODO: fetch the object
465 elif isinstance(_json, dict) and "value" not in _json:
466 _id = list(_json["value"].values())[0]
467 elif isinstance(_json, dict) and "value" in _json:
468 _id = _json["value"]
469 _json_device_info = await get_device_info(session, _url, _id)
470 if _json_device_info:
471 _json = _json_device_info
472
473 return await update_changed_flag(_json, resp.status, "create")
474
475
476 async def _delete(params, session):
477 _in_query_parameters = PAYLOAD_FORMAT["delete"]["query"].keys()
478 payload = prepare_payload(params, PAYLOAD_FORMAT["delete"])
479 subdevice_type = get_subdevice_type("/api/vcenter/resource-pool/{resource_pool}")
480 if subdevice_type and not params[subdevice_type]:
481 _json = await exists(params, session, build_url(params))
482 if _json:
483 params[subdevice_type] = _json["id"]
484 _url = (
485 "https://{vcenter_hostname}" "/api/vcenter/resource-pool/{resource_pool}"
486 ).format(**params) + gen_args(params, _in_query_parameters)
487 async with session.delete(_url, json=payload, **session_timeout(params)) as resp:
488 try:
489 if resp.headers["Content-Type"] == "application/json":
490 _json = await resp.json()
491 except KeyError:
492 _json = {}
493 return await update_changed_flag(_json, resp.status, "delete")
494
495
496 async def _update(params, session):
497 payload = prepare_payload(params, PAYLOAD_FORMAT["update"])
498 _url = (
499 "https://{vcenter_hostname}" "/api/vcenter/resource-pool/{resource_pool}"
500 ).format(**params)
501 async with session.get(_url, **session_timeout(params)) as resp:
502 _json = await resp.json()
503 if "value" in _json:
504 value = _json["value"]
505 else: # 7.0.2 and greater
506 value = _json
507 for k, v in value.items():
508 if k in payload:
509 if isinstance(payload[k], dict) and isinstance(v, dict):
510 to_delete = True
511 for _k in list(payload[k].keys()):
512 if payload[k][_k] != v.get(_k):
513 to_delete = False
514 if to_delete:
515 del payload[k]
516 elif payload[k] == v:
517 del payload[k]
518 elif payload[k] == {}:
519 del payload[k]
520
521 if payload == {} or payload == {"spec": {}}:
522 # Nothing has changed
523 if "value" not in _json: # 7.0.2
524 _json = {"value": _json}
525 _json["id"] = params.get("resource_pool")
526 return await update_changed_flag(_json, resp.status, "get")
527 async with session.patch(_url, json=payload, **session_timeout(params)) as resp:
528 try:
529 if resp.headers["Content-Type"] == "application/json":
530 _json = await resp.json()
531 except KeyError:
532 _json = {}
533 if "value" not in _json: # 7.0.2
534 _json = {"value": _json}
535
536 # e.g: content_configuration
537 if not _json and resp.status == 204:
538 async with session.get(_url, **session_timeout(params)) as resp_get:
539 _json_get = await resp_get.json()
540 if _json_get:
541 _json = _json_get
542
543 _json["id"] = params.get("resource_pool")
544 return await update_changed_flag(_json, resp.status, "update")
545
546
547 if __name__ == "__main__":
548 import asyncio
549
550 current_loop = asyncio.new_event_loop()
551 try:
552 asyncio.set_event_loop(current_loop)
553 current_loop.run_until_complete(main())
554 finally:
555 current_loop.close()