[PR #11095/2b4333a0 backport][stable-12] Use raise from in plugins (#11129)

Use raise from in plugins (#11095)

* Use raise from.

* Add changelog fragment.

(cherry picked from commit 2b4333a033)

Co-authored-by: Felix Fontein <felix@fontein.de>
This commit is contained in:
patchback[bot]
2025-11-12 21:00:39 +01:00
committed by GitHub
parent cddb570e0e
commit cc93dab0fd
46 changed files with 218 additions and 165 deletions

View File

@@ -124,7 +124,9 @@ class InventoryModule(BaseInventoryPlugin, Constructable):
# Create groups based on variable values and add the corresponding hosts to it
self._add_host_to_keyed_groups(self.get_option("keyed_groups"), host_attrs, host, strict=strict)
except Exception as e:
raise AnsibleParserError(f"Unable to fetch hosts from GitLab API, this was the original exception: {e}")
raise AnsibleParserError(
f"Unable to fetch hosts from GitLab API, this was the original exception: {e}"
) from e
def verify_file(self, path):
"""Return the possibly of a file being consumable by this plugin."""

View File

@@ -166,8 +166,10 @@ class InventoryModule(BaseInventoryPlugin, Constructable):
except Exception:
error_body = {"status": None}
if e.code == 404 and error_body.get("status") == "No objects found.":
raise AnsibleParserError("Host filter returned no data. Please confirm your host_filter value is valid")
raise AnsibleParserError(f"Unexpected data returned: {e} -- {error_body}")
raise AnsibleParserError(
"Host filter returned no data. Please confirm your host_filter value is valid"
) from e
raise AnsibleParserError(f"Unexpected data returned: {e} -- {error_body}") from e
response_body = response.read()
json_data = json.loads(response_body.decode("utf-8"))

View File

@@ -160,7 +160,7 @@ class InventoryModule(BaseInventoryPlugin, Constructable, Cacheable):
try:
self.instances = self.client.linode.instances()
except LinodeApiError as exception:
raise AnsibleError(f"Linode client raised: {exception}")
raise AnsibleError(f"Linode client raised: {exception}") from exception
def _add_groups(self):
"""Add Linode instance groups to the dynamic inventory."""

View File

@@ -213,7 +213,7 @@ class InventoryModule(BaseInventoryPlugin):
with open(path, "r") as json_file:
return json.load(json_file)
except (IOError, json.decoder.JSONDecodeError) as err:
raise AnsibleParserError(f"Could not load the test data from {to_native(path)}: {err}")
raise AnsibleParserError(f"Could not load the test data from {to_native(path)}: {err}") from err
def save_json_data(self, path, file_name=None):
"""save data as json
@@ -243,7 +243,7 @@ class InventoryModule(BaseInventoryPlugin):
with open(os.path.abspath(os.path.join(cwd, *path)), "w") as json_file:
json.dump(self.data, json_file)
except IOError as err:
raise AnsibleParserError(f"Could not save data: {err}")
raise AnsibleParserError(f"Could not save data: {err}") from err
def verify_file(self, path):
"""Check the config
@@ -602,7 +602,7 @@ class InventoryModule(BaseInventoryPlugin):
else:
path[instance_name][key] = value
except KeyError as err:
raise AnsibleParserError(f"Unable to store Information: {err}")
raise AnsibleParserError(f"Unable to store Information: {err}") from err
def extract_information_from_instance_configs(self):
"""Process configuration information
@@ -853,7 +853,7 @@ class InventoryModule(BaseInventoryPlugin):
except ValueError as err:
raise AnsibleParserError(
f"Error while parsing network range {self.groupby[group_name].get('attribute')}: {err}"
)
) from err
for instance_name in self.inventory.hosts:
if self.data["inventory"][instance_name].get("network_interfaces") is not None:
@@ -1203,6 +1203,6 @@ class InventoryModule(BaseInventoryPlugin):
self.trust_password = self.get_option("trust_password")
self.url = self.get_option("url")
except Exception as err:
raise AnsibleParserError(f"All correct options required: {err}")
raise AnsibleParserError(f"All correct options required: {err}") from err
# Call our internal helper to populate the dynamic inventory
self._populate()

View File

@@ -180,7 +180,7 @@ class InventoryModule(BaseInventoryPlugin, Constructable, Cacheable):
try:
self._nmap = get_bin_path("nmap")
except ValueError as e:
raise AnsibleParserError(f"nmap inventory plugin requires the nmap cli tool to work: {e}")
raise AnsibleParserError(f"nmap inventory plugin requires the nmap cli tool to work: {e}") from e
super().parse(inventory, loader, path, cache=cache)
@@ -265,7 +265,7 @@ class InventoryModule(BaseInventoryPlugin, Constructable, Cacheable):
try:
t_stdout = to_text(stdout, errors="surrogate_or_strict")
except UnicodeError as e:
raise AnsibleParserError(f"Invalid (non unicode) input returned: {e}")
raise AnsibleParserError(f"Invalid (non unicode) input returned: {e}") from e
for line in t_stdout.splitlines():
hits = self.find_host.match(line)
@@ -310,7 +310,7 @@ class InventoryModule(BaseInventoryPlugin, Constructable, Cacheable):
results[-1]["ports"] = ports
except Exception as e:
raise AnsibleParserError(f"failed to parse {to_native(path)}: {e} ")
raise AnsibleParserError(f"failed to parse {to_native(path)}: {e} ") from e
if cache_needs_update:
self._cache[cache_key] = results

View File

@@ -141,13 +141,13 @@ class InventoryModule(BaseInventoryPlugin):
try:
raw_data = to_text(response.read(), errors="surrogate_or_strict")
except UnicodeError:
raise AnsibleError("Incorrect encoding of fetched payload from Online servers")
except UnicodeError as e:
raise AnsibleError("Incorrect encoding of fetched payload from Online servers") from e
try:
return json.loads(raw_data)
except ValueError:
raise AnsibleError("Incorrect JSON payload")
except ValueError as e:
raise AnsibleError("Incorrect JSON payload") from e
@staticmethod
def extract_rpn_lookup_cache(rpn_list):

View File

@@ -122,10 +122,10 @@ class InventoryModule(BaseInventoryPlugin, Constructable):
with open(authfile, "r") as fp:
authstring = fp.read().rstrip()
username, password = authstring.split(":")
except (OSError, IOError):
raise AnsibleError(f"Could not find or read ONE_AUTH file at '{authfile}'")
except Exception:
raise AnsibleError(f"Error occurs when reading ONE_AUTH file at '{authfile}'")
except (OSError, IOError) as e:
raise AnsibleError(f"Could not find or read ONE_AUTH file at '{authfile}'") from e
except Exception as e:
raise AnsibleError(f"Error occurs when reading ONE_AUTH file at '{authfile}'") from e
auth_params = namedtuple("auth", ("url", "username", "password"))
@@ -167,7 +167,7 @@ class InventoryModule(BaseInventoryPlugin, Constructable):
try:
vm_pool = one_client.vmpool.infoextended(-2, -1, -1, 3)
except Exception as e:
raise AnsibleError(f"Something happened during XML-RPC call: {e}")
raise AnsibleError(f"Something happened during XML-RPC call: {e}") from e
return vm_pool

View File

@@ -143,16 +143,16 @@ def _fetch_information(token, url):
try:
response = open_url(paginated_url, headers={"X-Auth-Token": token, "Content-type": "application/json"})
except Exception as e:
raise AnsibleError(f"Error while fetching {url}: {e}")
raise AnsibleError(f"Error while fetching {url}: {e}") from e
try:
raw_json = json.loads(to_text(response.read()))
except ValueError:
raise AnsibleError("Incorrect JSON payload")
except ValueError as e:
raise AnsibleError("Incorrect JSON payload") from e
try:
results.extend(raw_json["servers"])
except KeyError:
raise AnsibleError("Incorrect format from the Scaleway API response")
except KeyError as e:
raise AnsibleError("Incorrect format from the Scaleway API response") from e
link = response.headers["Link"]
if not link:

View File

@@ -312,7 +312,7 @@ class InventoryModule(BaseInventoryPlugin, Constructable, Cacheable):
try:
self._vbox_path = get_bin_path(self.VBOX)
except ValueError as e:
raise AnsibleParserError(e)
raise AnsibleParserError(e) from e
super().parse(inventory, loader, path)
@@ -354,7 +354,7 @@ class InventoryModule(BaseInventoryPlugin, Constructable, Cacheable):
try:
p = Popen(cmd, stdout=PIPE)
except Exception as e:
raise AnsibleParserError(str(e))
raise AnsibleParserError(str(e)) from e
source_data = p.stdout.read().splitlines()