Debian Codegraph @

ansible_collections/community/general/plugins/module_utils/_manageiq.py

raw
1 #
2 # Copyright (c) 2017, Daniel Korn <[email protected]>
3 #
4 # This code is part of Ansible, but is an independent component.
5 # This particular file snippet, and this file snippet only, is BSD licensed.
6 # Modules you write using this snippet, which is embedded dynamically by Ansible
7 # still belong to the author of the module, and may assign their own license
8 # to the complete work.
9 #
10 # Simplified BSD License (see LICENSES/BSD-2-Clause.txt or https://opensource.org/licenses/BSD-2-Clause)
11 # SPDX-License-Identifier: BSD-2-Clause
12
13 # Note that this module util is **PRIVATE** to the collection. It can have breaking changes at any time.
14 # Do not use this from other collections or standalone plugins/modules!
15
16 from __future__ import annotations
17
18 import os
19 import traceback
20 import typing as t
21
22 from ansible.module_utils.basic import missing_required_lib
23
24 if t.TYPE_CHECKING:
25 from ansible.module_utils.basic import AnsibleModule
26
27 CLIENT_IMP_ERR = None
28 try:
29 from manageiq_client.api import ManageIQClient
30
31 HAS_CLIENT = True
32 except ImportError:
33 CLIENT_IMP_ERR = traceback.format_exc()
34 HAS_CLIENT = False
35
36
37 def manageiq_argument_spec() -> dict[str, t.Any]:
38 options = dict(
39 url=dict(default=os.environ.get("MIQ_URL", None)),
40 username=dict(default=os.environ.get("MIQ_USERNAME", None)),
41 password=dict(default=os.environ.get("MIQ_PASSWORD", None), no_log=True),
42 token=dict(default=os.environ.get("MIQ_TOKEN", None), no_log=True),
43 validate_certs=dict(default=True, type="bool", aliases=["verify_ssl"]),
44 ca_cert=dict(required=False, default=None, aliases=["ca_bundle_path"]),
45 )
46
47 return dict(
48 manageiq_connection=dict(type="dict", apply_defaults=True, options=options),
49 )
50
51
52 def check_client(module: AnsibleModule) -> None:
53 if not HAS_CLIENT:
54 module.fail_json(msg=missing_required_lib("manageiq-client"), exception=CLIENT_IMP_ERR)
55
56
57 def validate_connection_params(module: AnsibleModule) -> dict[str, t.Any]:
58 params: dict[str, t.Any] = module.params["manageiq_connection"]
59 url: str | None = params["url"]
60 token: str | None = params["token"]
61 username: str | None = params["username"]
62 password: str | None = params["password"]
63
64 if (url and username and password) or (url and token):
65 return params
66 for arg in ["url", "username", "password"]:
67 if params[arg] in (None, ""):
68 module.fail_json(msg=f"missing required argument: manageiq_connection[{arg}]")
69 raise AssertionError("should be unreachable")
70
71
72 def manageiq_entities() -> dict[str, str]:
73 return {
74 "provider": "providers",
75 "host": "hosts",
76 "vm": "vms",
77 "category": "categories",
78 "cluster": "clusters",
79 "data store": "data_stores",
80 "group": "groups",
81 "resource pool": "resource_pools",
82 "service": "services",
83 "service template": "service_templates",
84 "template": "templates",
85 "tenant": "tenants",
86 "user": "users",
87 "blueprint": "blueprints",
88 }
89
90
91 class ManageIQ:
92 """
93 class encapsulating ManageIQ API client.
94 """
95
96 def __init__(self, module: AnsibleModule) -> None:
97 # handle import errors
98 check_client(module)
99
100 params = validate_connection_params(module)
101
102 url = params["url"]
103 username = params["username"]
104 password = params["password"]
105 token = params["token"]
106 verify_ssl = params["validate_certs"]
107 ca_bundle_path = params["ca_cert"]
108
109 self._module = module
110 self._api_url = f"{url}/api"
111 self._auth = dict(user=username, password=password, token=token)
112 try:
113 self._client = ManageIQClient(
114 self._api_url, self._auth, verify_ssl=verify_ssl, ca_bundle_path=ca_bundle_path
115 )
116 except Exception as e:
117 self.module.fail_json(msg=f"failed to open connection ({url}): {e}")
118
119 @property
120 def module(self) -> AnsibleModule:
121 """Ansible module module
122
123 Returns:
124 the ansible module
125 """
126 return self._module
127
128 @property
129 def api_url(self) -> str:
130 """Base ManageIQ API
131
132 Returns:
133 the base ManageIQ API
134 """
135 return self._api_url
136
137 @property
138 def client(self):
139 """ManageIQ client
140
141 Returns:
142 the ManageIQ client
143 """
144 return self._client
145
146 def find_collection_resource_by(self, collection_name, **params):
147 """Searches the collection resource by the collection name and the param passed.
148
149 Returns:
150 the resource as an object if it exists in manageiq, None otherwise.
151 """
152 try:
153 entity = self.client.collections.__getattribute__(collection_name).get(**params)
154 except ValueError:
155 return None
156 except Exception as e:
157 self.module.fail_json(msg=f"failed to find resource {e}")
158 return vars(entity)
159
160 def find_collection_resource_or_fail(self, collection_name, **params):
161 """Searches the collection resource by the collection name and the param passed.
162
163 Returns:
164 the resource as an object if it exists in manageiq, Fail otherwise.
165 """
166 resource = self.find_collection_resource_by(collection_name, **params)
167 if resource:
168 return resource
169 else:
170 msg = f"{collection_name} where {params} does not exist in manageiq"
171 self.module.fail_json(msg=msg)
172
173 def policies(self, resource_id, resource_type, resource_name):
174 manageiq = ManageIQ(self.module)
175
176 # query resource id, fail if resource does not exist
177 if resource_id is None:
178 resource_id = manageiq.find_collection_resource_or_fail(resource_type, name=resource_name)["id"]
179
180 return ManageIQPolicies(manageiq, resource_type, resource_id)
181
182 def query_resource_id(self, resource_type, resource_name):
183 """Query the resource name in ManageIQ.
184
185 Returns:
186 the resource ID if it exists in ManageIQ, Fail otherwise.
187 """
188 resource = self.find_collection_resource_by(resource_type, name=resource_name)
189 if resource:
190 return resource["id"]
191 else:
192 msg = f"{resource_name} {resource_type} does not exist in manageiq"
193 self.module.fail_json(msg=msg)
194
195
196 class ManageIQPolicies:
197 """
198 Object to execute policies management operations of manageiq resources.
199 """
200
201 def __init__(self, manageiq: ManageIQ, resource_type, resource_id):
202 self.manageiq = manageiq
203
204 self.module = self.manageiq.module
205 self.api_url = self.manageiq.api_url
206 self.client = self.manageiq.client
207
208 self.resource_type = resource_type
209 self.resource_id = resource_id
210 self.resource_url = f"{self.api_url}/{resource_type}/{resource_id}"
211
212 def query_profile_href(self, profile):
213 """Add or Update the policy_profile href field
214
215 Example:
216 {name: STR, ...} => {name: STR, href: STR}
217 """
218 resource = self.manageiq.find_collection_resource_or_fail("policy_profiles", **profile)
219 return dict(name=profile["name"], href=resource["href"])
220
221 def query_resource_profiles(self):
222 """Returns a set of the profile objects objects assigned to the resource"""
223 url = f"{self.resource_url}/policy_profiles?expand=resources"
224 try:
225 response = self.client.get(url)
226 except Exception as e:
227 msg = f"Failed to query {self.resource_type} policies: {e}"
228 self.module.fail_json(msg=msg)
229
230 resources = response.get("resources", [])
231
232 # clean the returned rest api profile object to look like:
233 # {profile_name: STR, profile_description: STR, policies: ARR<POLICIES>}
234 profiles = [self.clean_profile_object(profile) for profile in resources]
235
236 return profiles
237
238 def query_profile_policies(self, profile_id):
239 """Returns a set of the policy objects assigned to the resource"""
240 url = f"{self.api_url}/policy_profiles/{profile_id}?expand=policies"
241 try:
242 response = self.client.get(url)
243 except Exception as e:
244 msg = f"Failed to query {self.resource_type} policies: {e}"
245 self.module.fail_json(msg=msg)
246
247 resources = response.get("policies", [])
248
249 # clean the returned rest api policy object to look like:
250 # {name: STR, description: STR, active: BOOL}
251 policies = [self.clean_policy_object(policy) for policy in resources]
252
253 return policies
254
255 def clean_policy_object(self, policy):
256 """Clean a policy object to have human readable form of:
257 {
258 name: STR,
259 description: STR,
260 active: BOOL
261 }
262 """
263 name = policy.get("name")
264 description = policy.get("description")
265 active = policy.get("active")
266
267 return dict(name=name, description=description, active=active)
268
269 def clean_profile_object(self, profile):
270 """Clean a profile object to have human readable form of:
271 {
272 profile_name: STR,
273 profile_description: STR,
274 policies: ARR<POLICIES>
275 }
276 """
277 profile_id = profile["id"]
278 name = profile.get("name")
279 description = profile.get("description")
280 policies = self.query_profile_policies(profile_id)
281
282 return dict(profile_name=name, profile_description=description, policies=policies)
283
284 def profiles_to_update(self, profiles, action):
285 """Create a list of policies we need to update in ManageIQ.
286
287 Returns:
288 Whether or not a change took place and a message describing the
289 operation executed.
290 """
291 profiles_to_post = []
292 assigned_profiles = self.query_resource_profiles()
293
294 # make a list of assigned full profile names strings
295 # e.g. ['openscap profile', ...]
296 assigned_profiles_set = {profile["profile_name"] for profile in assigned_profiles}
297
298 for profile in profiles:
299 assigned = profile.get("name") in assigned_profiles_set
300
301 if (action == "unassign" and assigned) or (action == "assign" and not assigned):
302 # add/update the policy profile href field
303 # {name: STR, ...} => {name: STR, href: STR}
304 profile = self.query_profile_href(profile)
305 profiles_to_post.append(profile)
306
307 return profiles_to_post
308
309 def assign_or_unassign_profiles(self, profiles, action):
310 """Perform assign/unassign action"""
311 # get a list of profiles needed to be changed
312 profiles_to_post = self.profiles_to_update(profiles, action)
313 if not profiles_to_post:
314 return dict(changed=False, msg=f"Profiles {profiles} already {action}ed, nothing to do")
315
316 # try to assign or unassign profiles to resource
317 url = f"{self.resource_url}/policy_profiles"
318 try:
319 response = self.client.post(url, action=action, resources=profiles_to_post)
320 except Exception as e:
321 msg = f"Failed to {action} profile: {e}"
322 self.module.fail_json(msg=msg)
323
324 # check all entities in result to be successful
325 for result in response["results"]:
326 if not result["success"]:
327 msg = f"Failed to {action}: {result['message']}"
328 self.module.fail_json(msg=msg)
329
330 # successfully changed all needed profiles
331 return dict(changed=True, msg=f"Successfully {action}ed profiles: {profiles}")
332
333
334 class ManageIQTags:
335 """
336 Object to execute tags management operations of manageiq resources.
337 """
338
339 def __init__(self, manageiq: ManageIQ, resource_type, resource_id):
340 self.manageiq = manageiq
341
342 self.module = self.manageiq.module
343 self.api_url = self.manageiq.api_url
344 self.client = self.manageiq.client
345
346 self.resource_type = resource_type
347 self.resource_id = resource_id
348 self.resource_url = f"{self.api_url}/{resource_type}/{resource_id}"
349
350 def full_tag_name(self, tag):
351 """Returns the full tag name in manageiq"""
352 return f"/managed/{tag['category']}/{tag['name']}"
353
354 def clean_tag_object(self, tag):
355 """Clean a tag object to have human readable form of:
356 {
357 full_name: STR,
358 name: STR,
359 display_name: STR,
360 category: STR
361 }
362 """
363 full_name = tag.get("name")
364 categorization = tag.get("categorization", {})
365
366 return dict(
367 full_name=full_name,
368 name=categorization.get("name"),
369 display_name=categorization.get("display_name"),
370 category=categorization.get("category", {}).get("name"),
371 )
372
373 def query_resource_tags(self):
374 """Returns a set of the tag objects assigned to the resource"""
375 url = f"{self.resource_url}/tags?expand=resources&attributes=categorization"
376 try:
377 response = self.client.get(url)
378 except Exception as e:
379 msg = f"Failed to query {self.resource_type} tags: {e}"
380 self.module.fail_json(msg=msg)
381
382 resources = response.get("resources", [])
383
384 # clean the returned rest api tag object to look like:
385 # {full_name: STR, name: STR, display_name: STR, category: STR}
386 tags = [self.clean_tag_object(tag) for tag in resources]
387
388 return tags
389
390 def tags_to_update(self, tags, action):
391 """Create a list of tags we need to update in ManageIQ.
392
393 Returns:
394 Whether or not a change took place and a message describing the
395 operation executed.
396 """
397 tags_to_post = []
398 assigned_tags = self.query_resource_tags()
399
400 # make a list of assigned full tag names strings
401 # e.g. ['/managed/environment/prod', ...]
402 assigned_tags_set = {tag["full_name"] for tag in assigned_tags}
403
404 for tag in tags:
405 assigned = self.full_tag_name(tag) in assigned_tags_set
406
407 if assigned and action == "unassign":
408 tags_to_post.append(tag)
409 elif (not assigned) and action == "assign":
410 tags_to_post.append(tag)
411
412 return tags_to_post
413
414 def assign_or_unassign_tags(self, tags, action):
415 """Perform assign/unassign action"""
416 # get a list of tags needed to be changed
417 tags_to_post = self.tags_to_update(tags, action)
418 if not tags_to_post:
419 return dict(changed=False, msg=f"Tags already {action}ed, nothing to do")
420
421 # try to assign or unassign tags to resource
422 url = f"{self.resource_url}/tags"
423 try:
424 response = self.client.post(url, action=action, resources=tags)
425 except Exception as e:
426 msg = f"Failed to {action} tag: {e}"
427 self.module.fail_json(msg=msg)
428
429 # check all entities in result to be successful
430 for result in response["results"]:
431 if not result["success"]:
432 msg = f"Failed to {action}: {result['message']}"
433 self.module.fail_json(msg=msg)
434
435 # successfully changed all needed tags
436 return dict(changed=True, msg=f"Successfully {action}ed tags")