Debian Codegraph @

ansible_collections/community/general/plugins/modules/manageiq_tenant.py

raw
1 #!/usr/bin/python
2 # Copyright (c) 2018, Evert Mulder (base on manageiq_user.py by Daniel Korn <[email protected]>)
3 # GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
4 # SPDX-License-Identifier: GPL-3.0-or-later
5
6 from __future__ import annotations
7
8 DOCUMENTATION = r"""
9 module: manageiq_tenant
10
11 short_description: Management of tenants in ManageIQ
12 extends_documentation_fragment:
13 - community.general._manageiq
14 - community.general._attributes
15
16 author: Evert Mulder (@evertmulder)
17 description:
18 - The manageiq_tenant module supports adding, updating and deleting tenants in ManageIQ.
19 requirements:
20 - manageiq-client
21 attributes:
22 check_mode:
23 support: none
24 diff_mode:
25 support: none
26 options:
27 state:
28 type: str
29 description:
30 - V(absent) - tenant should not exist,
31 - V(present) - tenant should be.
32 choices: ['absent', 'present']
33 default: 'present'
34 name:
35 type: str
36 description:
37 - The tenant name.
38 required: true
39 default:
40 description:
41 type: str
42 description:
43 - The tenant description.
44 required: true
45 default:
46 parent_id:
47 type: int
48 description:
49 - The ID of the parent tenant. If not supplied the root tenant is used.
50 - The O(parent_id) takes president over O(parent) when supplied.
51 default:
52 parent:
53 type: str
54 description:
55 - The name of the parent tenant. If not supplied and no O(parent_id) is supplied the root tenant is used.
56 default:
57 quotas:
58 type: dict
59 description:
60 - The tenant quotas.
61 - All parameters case sensitive.
62 - 'Valid attributes are:'
63 - '- V(cpu_allocated) (int): use null to remove the quota.'
64 - '- V(mem_allocated) (GB): use null to remove the quota.'
65 - '- V(storage_allocated) (GB): use null to remove the quota.'
66 - '- V(vms_allocated) (int): use null to remove the quota.'
67 - '- V(templates_allocated) (int): use null to remove the quota.'
68 default: {}
69 """
70
71 EXAMPLES = r"""
72 - name: Update the root tenant in ManageIQ
73 community.general.manageiq_tenant:
74 name: 'My Company'
75 description: 'My company name'
76 manageiq_connection:
77 url: 'http://127.0.0.1:3000'
78 username: 'admin'
79 password: 'smartvm'
80 validate_certs: false # only do this when you trust the network!
81
82 - name: Create a tenant in ManageIQ
83 community.general.manageiq_tenant:
84 name: 'Dep1'
85 description: 'Manufacturing department'
86 parent_id: 1
87 manageiq_connection:
88 url: 'http://127.0.0.1:3000'
89 username: 'admin'
90 password: 'smartvm'
91 validate_certs: false # only do this when you trust the network!
92
93 - name: Delete a tenant in ManageIQ
94 community.general.manageiq_tenant:
95 state: 'absent'
96 name: 'Dep1'
97 parent_id: 1
98 manageiq_connection:
99 url: 'http://127.0.0.1:3000'
100 username: 'admin'
101 password: 'smartvm'
102 validate_certs: false # only do this when you trust the network!
103
104 - name: Set tenant quota for cpu_allocated, mem_allocated, remove quota for vms_allocated
105 community.general.manageiq_tenant:
106 name: 'Dep1'
107 parent_id: 1
108 quotas:
109 - cpu_allocated: 100
110 - mem_allocated: 50
111 - vms_allocated:
112 manageiq_connection:
113 url: 'http://127.0.0.1:3000'
114 username: 'admin'
115 password: 'smartvm'
116 validate_certs: false # only do this when you trust the network!
117
118
119 - name: Delete a tenant in ManageIQ using a token
120 community.general.manageiq_tenant:
121 state: 'absent'
122 name: 'Dep1'
123 parent_id: 1
124 manageiq_connection:
125 url: 'http://127.0.0.1:3000'
126 token: 'sometoken'
127 validate_certs: false # only do this when you trust the network!
128 """
129
130 RETURN = r"""
131 tenant:
132 description: The tenant.
133 returned: success
134 type: complex
135 contains:
136 id:
137 description: The tenant ID.
138 returned: success
139 type: int
140 name:
141 description: The tenant name.
142 returned: success
143 type: str
144 description:
145 description: The tenant description.
146 returned: success
147 type: str
148 parent_id:
149 description: The ID of the parent tenant.
150 returned: success
151 type: int
152 quotas:
153 description: List of tenant quotas.
154 returned: success
155 type: list
156 sample:
157 cpu_allocated: 100
158 mem_allocated: 50
159 """
160
161 from ansible.module_utils.basic import AnsibleModule
162
163 from ansible_collections.community.general.plugins.module_utils._manageiq import ManageIQ, manageiq_argument_spec
164
165
166 class ManageIQTenant:
167 """
168 Object to execute tenant management operations in manageiq.
169 """
170
171 def __init__(self, manageiq):
172 self.manageiq = manageiq
173
174 self.module = self.manageiq.module
175 self.api_url = self.manageiq.api_url
176 self.client = self.manageiq.client
177
178 def tenant(self, name, parent_id, parent):
179 """Search for tenant object by name and parent_id or parent
180 or the root tenant if no parent or parent_id is supplied.
181 Returns:
182 the parent tenant, None for the root tenant
183 the tenant or None if tenant was not found.
184 """
185
186 if parent_id:
187 parent_tenant_res = self.client.collections.tenants.find_by(id=parent_id)
188 if not parent_tenant_res:
189 self.module.fail_json(msg=f"Parent tenant with id '{parent_id}' not found in manageiq")
190 parent_tenant = parent_tenant_res[0]
191 tenants = self.client.collections.tenants.find_by(name=name)
192
193 for tenant in tenants:
194 try:
195 ancestry = tenant["ancestry"]
196 except AttributeError:
197 ancestry = None
198
199 if ancestry:
200 tenant_parent_id = int(ancestry.split("/")[-1])
201 if int(tenant_parent_id) == parent_id:
202 return parent_tenant, tenant
203
204 return parent_tenant, None
205 else:
206 if parent:
207 parent_tenant_res = self.client.collections.tenants.find_by(name=parent)
208 if not parent_tenant_res:
209 self.module.fail_json(msg=f"Parent tenant '{parent}' not found in manageiq")
210
211 if len(parent_tenant_res) > 1:
212 self.module.fail_json(msg=f"Multiple parent tenants not found in manageiq with name '{parent}'")
213
214 parent_tenant = parent_tenant_res[0]
215 parent_id = int(parent_tenant["id"])
216 tenants = self.client.collections.tenants.find_by(name=name)
217
218 for tenant in tenants:
219 try:
220 ancestry = tenant["ancestry"]
221 except AttributeError:
222 ancestry = None
223
224 if ancestry:
225 tenant_parent_id = int(ancestry.split("/")[-1])
226 if tenant_parent_id == parent_id:
227 return parent_tenant, tenant
228
229 return parent_tenant, None
230 else:
231 # No parent or parent id supplied we select the root tenant
232 return None, self.client.collections.tenants.find_by(ancestry=None)[0]
233
234 def compare_tenant(self, tenant, name, description):
235 """Compare tenant fields with new field values.
236
237 Returns:
238 false if tenant fields have some difference from new fields, true o/w.
239 """
240 found_difference = (name and tenant["name"] != name) or (description and tenant["description"] != description)
241
242 return not found_difference
243
244 def delete_tenant(self, tenant):
245 """Deletes a tenant from manageiq.
246
247 Returns:
248 dict with `msg` and `changed`
249 """
250 try:
251 url = f"{self.api_url}/tenants/{tenant['id']}"
252 result = self.client.post(url, action="delete")
253 except Exception as e:
254 self.module.fail_json(msg=f"failed to delete tenant {tenant['name']}: {e}")
255
256 if result["success"] is False:
257 self.module.fail_json(msg=result["message"])
258
259 return dict(changed=True, msg=result["message"])
260
261 def edit_tenant(self, tenant, name, description):
262 """Edit a manageiq tenant.
263
264 Returns:
265 dict with `msg` and `changed`
266 """
267 resource = dict(name=name, description=description, use_config_for_attributes=False)
268
269 # check if we need to update ( compare_tenant is true is no difference found )
270 if self.compare_tenant(tenant, name, description):
271 return dict(changed=False, msg=f"tenant {tenant['name']} is not changed.", tenant=tenant["_data"])
272
273 # try to update tenant
274 try:
275 self.client.post(tenant["href"], action="edit", resource=resource)
276 except Exception as e:
277 self.module.fail_json(msg=f"failed to update tenant {tenant['name']}: {e}")
278
279 return dict(changed=True, msg=f"successfully updated the tenant with id {tenant['id']}")
280
281 def create_tenant(self, name, description, parent_tenant):
282 """Creates the tenant in manageiq.
283
284 Returns:
285 dict with `msg`, `changed` and `tenant_id`
286 """
287 parent_id = parent_tenant["id"]
288 # check for required arguments
289 for key, value in dict(name=name, description=description, parent_id=parent_id).items():
290 if value in (None, ""):
291 self.module.fail_json(msg=f"missing required argument: {key}")
292
293 url = f"{self.api_url}/tenants"
294
295 resource = {"name": name, "description": description, "parent": {"id": parent_id}}
296
297 try:
298 result = self.client.post(url, action="create", resource=resource)
299 tenant_id = result["results"][0]["id"]
300 except Exception as e:
301 self.module.fail_json(msg=f"failed to create tenant {name}: {e}")
302
303 return dict(
304 changed=True, msg=f"successfully created tenant '{name}' with id '{tenant_id}'", tenant_id=tenant_id
305 )
306
307 def tenant_quota(self, tenant, quota_key):
308 """Search for tenant quota object by tenant and quota_key.
309 Returns:
310 the quota for the tenant, or None if the tenant quota was not found.
311 """
312
313 tenant_quotas = self.client.get(f"{tenant['href']}/quotas?expand=resources&filter[]=name={quota_key}")
314
315 return tenant_quotas["resources"]
316
317 def tenant_quotas(self, tenant):
318 """Search for tenant quotas object by tenant.
319 Returns:
320 the quotas for the tenant, or None if no tenant quotas were not found.
321 """
322
323 tenant_quotas = self.client.get(f"{tenant['href']}/quotas?expand=resources")
324
325 return tenant_quotas["resources"]
326
327 def update_tenant_quotas(self, tenant, quotas):
328 """Creates the tenant quotas in manageiq.
329
330 Returns:
331 dict with `msg` and `changed`
332 """
333
334 changed = False
335 messages = []
336 for quota_key, quota_value in quotas.items():
337 current_quota_filtered = self.tenant_quota(tenant, quota_key)
338 if current_quota_filtered:
339 current_quota = current_quota_filtered[0]
340 else:
341 current_quota = None
342
343 if quota_value:
344 # Change the byte values to GB
345 if quota_key in ["storage_allocated", "mem_allocated"]:
346 quota_value_int = int(quota_value) * 1024 * 1024 * 1024
347 else:
348 quota_value_int = int(quota_value)
349 if current_quota:
350 res = self.edit_tenant_quota(tenant, current_quota, quota_key, quota_value_int)
351 else:
352 res = self.create_tenant_quota(tenant, quota_key, quota_value_int)
353 else:
354 if current_quota:
355 res = self.delete_tenant_quota(tenant, current_quota)
356 else:
357 res = dict(changed=False, msg=f"tenant quota '{quota_key}' does not exist")
358
359 if res["changed"]:
360 changed = True
361
362 messages.append(res["msg"])
363
364 return dict(changed=changed, msg=", ".join(messages))
365
366 def edit_tenant_quota(self, tenant, current_quota, quota_key, quota_value):
367 """Update the tenant quotas in manageiq.
368
369 Returns:
370 result
371 """
372
373 if current_quota["value"] == quota_value:
374 return dict(changed=False, msg=f"tenant quota {quota_key} already has value {quota_value}")
375 else:
376 url = f"{tenant['href']}/quotas/{current_quota['id']}"
377 resource = {"value": quota_value}
378 try:
379 self.client.post(url, action="edit", resource=resource)
380 except Exception as e:
381 self.module.fail_json(msg=f"failed to update tenant quota {quota_key}: {e}")
382
383 return dict(changed=True, msg=f"successfully updated tenant quota {quota_key}")
384
385 def create_tenant_quota(self, tenant, quota_key, quota_value):
386 """Creates the tenant quotas in manageiq.
387
388 Returns:
389 result
390 """
391 url = f"{tenant['href']}/quotas"
392 resource = {"name": quota_key, "value": quota_value}
393 try:
394 self.client.post(url, action="create", resource=resource)
395 except Exception as e:
396 self.module.fail_json(msg=f"failed to create tenant quota {quota_key}: {e}")
397
398 return dict(changed=True, msg=f"successfully created tenant quota {quota_key}")
399
400 def delete_tenant_quota(self, tenant, quota):
401 """deletes the tenant quotas in manageiq.
402
403 Returns:
404 result
405 """
406 try:
407 result = self.client.post(quota["href"], action="delete")
408 except Exception as e:
409 self.module.fail_json(msg=f"failed to delete tenant quota '{quota['name']}': {e}")
410
411 return dict(changed=True, msg=result["message"])
412
413 def create_tenant_response(self, tenant, parent_tenant):
414 """Creates the ansible result object from a manageiq tenant entity
415
416 Returns:
417 a dict with the tenant id, name, description, parent id,
418 quota's
419 """
420 tenant_quotas = self.create_tenant_quotas_response(tenant["tenant_quotas"])
421
422 try:
423 ancestry = tenant["ancestry"]
424 tenant_parent_id = ancestry.split("/")[-1]
425 except AttributeError:
426 # The root tenant does not return the ancestry attribute
427 tenant_parent_id = None
428
429 return dict(
430 id=tenant["id"],
431 name=tenant["name"],
432 description=tenant["description"],
433 parent_id=tenant_parent_id,
434 quotas=tenant_quotas,
435 )
436
437 @staticmethod
438 def create_tenant_quotas_response(tenant_quotas):
439 """Creates the ansible result object from a manageiq tenant_quotas entity
440
441 Returns:
442 a dict with the applied quotas, name and value
443 """
444
445 if not tenant_quotas:
446 return {}
447
448 result = {}
449 for quota in tenant_quotas:
450 if quota["unit"] == "bytes":
451 value = float(quota["value"]) / (1024 * 1024 * 1024)
452 else:
453 value = quota["value"]
454 result[quota["name"]] = value
455 return result
456
457
458 def main():
459 argument_spec = dict(
460 name=dict(required=True, type="str"),
461 description=dict(required=True, type="str"),
462 parent_id=dict(type="int"),
463 parent=dict(type="str"),
464 state=dict(choices=["absent", "present"], default="present"),
465 quotas=dict(type="dict", default={}),
466 )
467 # add the manageiq connection arguments to the arguments
468 argument_spec.update(manageiq_argument_spec())
469
470 module = AnsibleModule(argument_spec=argument_spec)
471
472 name = module.params["name"]
473 description = module.params["description"]
474 parent_id = module.params["parent_id"]
475 parent = module.params["parent"]
476 state = module.params["state"]
477 quotas = module.params["quotas"]
478
479 manageiq = ManageIQ(module)
480 manageiq_tenant = ManageIQTenant(manageiq)
481
482 parent_tenant, tenant = manageiq_tenant.tenant(name, parent_id, parent)
483
484 # tenant should not exist
485 if state == "absent":
486 # if we have a tenant, delete it
487 if tenant:
488 res_args = manageiq_tenant.delete_tenant(tenant)
489 # if we do not have a tenant, nothing to do
490 else:
491 if parent_id:
492 msg = f"tenant '{name}' with parent_id {int(parent_id)} does not exist in manageiq"
493 else:
494 msg = f"tenant '{name}' with parent '{parent}' does not exist in manageiq"
495
496 res_args = dict(changed=False, msg=msg)
497
498 # tenant should exist
499 if state == "present":
500 # if we have a tenant, edit it
501 if tenant:
502 res_args = manageiq_tenant.edit_tenant(tenant, name, description)
503
504 # if we do not have a tenant, create it
505 else:
506 res_args = manageiq_tenant.create_tenant(name, description, parent_tenant)
507 tenant = manageiq.client.get_entity("tenants", res_args["tenant_id"])
508
509 # quotas as supplied and we have a tenant
510 if quotas:
511 tenant_quotas_res = manageiq_tenant.update_tenant_quotas(tenant, quotas)
512 if tenant_quotas_res["changed"]:
513 res_args["changed"] = True
514 res_args["tenant_quotas_msg"] = tenant_quotas_res["msg"]
515
516 tenant.reload(expand="resources", attributes=["tenant_quotas"])
517 res_args["tenant"] = manageiq_tenant.create_tenant_response(tenant, parent_tenant)
518
519 module.exit_json(**res_args)
520
521
522 if __name__ == "__main__":
523 main()