mirror of
https://github.com/ansible-collections/community.general.git
synced 2026-05-08 06:12:51 +00:00
[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:
@@ -107,6 +107,6 @@ class LookupModule(LookupBase):
|
||||
with open(path, "rb") as f:
|
||||
result.append(base64.b64encode(f.read()).decode("utf-8"))
|
||||
except Exception as exc:
|
||||
raise AnsibleLookupError(f"Error while reading {path}: {exc}")
|
||||
raise AnsibleLookupError(f"Error while reading {path}: {exc}") from exc
|
||||
|
||||
return result
|
||||
|
||||
@@ -77,8 +77,8 @@ class LookupModule(LookupBase):
|
||||
continue
|
||||
parsed = str(arg_raw)
|
||||
setattr(self, arg, parsed)
|
||||
except ValueError:
|
||||
raise AnsibleError(f"can't parse arg {arg}={arg_raw} as string")
|
||||
except ValueError as e:
|
||||
raise AnsibleError(f"can't parse arg {arg}={arg_raw} as string") from e
|
||||
if args:
|
||||
raise AnsibleError(f"unrecognized arguments to with_sequence: {list(args.keys())!r}")
|
||||
|
||||
|
||||
@@ -122,7 +122,7 @@ class LookupModule(LookupBase):
|
||||
try:
|
||||
data = load_collection_meta(collection_pkg, no_version=no_version)
|
||||
except Exception as exc:
|
||||
raise AnsibleLookupError(f"Error while loading metadata for {term}: {exc}")
|
||||
raise AnsibleLookupError(f"Error while loading metadata for {term}: {exc}") from exc
|
||||
|
||||
result.append(data.get("version", no_version))
|
||||
|
||||
|
||||
@@ -170,7 +170,7 @@ class LookupModule(LookupBase):
|
||||
else:
|
||||
values.append(to_text(results[1]["Value"]))
|
||||
except Exception as e:
|
||||
raise AnsibleError(f"Error locating '{term}' in kv store. Error was {e}")
|
||||
raise AnsibleError(f"Error locating '{term}' in kv store. Error was {e}") from e
|
||||
|
||||
return values
|
||||
|
||||
@@ -194,6 +194,6 @@ class LookupModule(LookupBase):
|
||||
raise AnsibleAssertionError(f"{name} not a valid consul lookup parameter")
|
||||
paramvals[name] = value
|
||||
except (ValueError, AssertionError) as e:
|
||||
raise AnsibleError(e)
|
||||
raise AnsibleError(e) from e
|
||||
|
||||
return paramvals
|
||||
|
||||
@@ -145,9 +145,9 @@ class LookupModule(LookupBase):
|
||||
for term in terms:
|
||||
try:
|
||||
ret.append(credstash.getSecret(term, version, region, table, context=context, **kwargs_pass))
|
||||
except credstash.ItemNotFound:
|
||||
raise AnsibleError(f"Key {term} not found")
|
||||
except credstash.ItemNotFound as e:
|
||||
raise AnsibleError(f"Key {term} not found") from e
|
||||
except Exception as e:
|
||||
raise AnsibleError(f"Encountered exception while fetching {term}: {e}")
|
||||
raise AnsibleError(f"Encountered exception while fetching {term}: {e}") from e
|
||||
|
||||
return ret
|
||||
|
||||
@@ -164,11 +164,11 @@ class CyberarkPassword:
|
||||
result_dict[output_names[i]] = to_native(output_values[i])
|
||||
|
||||
except subprocess.CalledProcessError as e:
|
||||
raise AnsibleError(e.output)
|
||||
raise AnsibleError(e.output) from e
|
||||
except OSError as e:
|
||||
raise AnsibleError(
|
||||
f"ERROR - AIM not installed or clipasswordsdk not in standard location. ERROR=({e.errno}) => {e.strerror} "
|
||||
)
|
||||
) from e
|
||||
|
||||
return [result_dict]
|
||||
|
||||
|
||||
@@ -174,7 +174,7 @@ class LookupModule(LookupBase):
|
||||
try:
|
||||
values = self.__evaluate(expression, templar, variables=vars)
|
||||
except Exception as e:
|
||||
raise AnsibleLookupError(f'Caught "{e}" while evaluating {key!r} with item == {current!r}')
|
||||
raise AnsibleLookupError(f'Caught "{e}" while evaluating {key!r} with item == {current!r}') from e
|
||||
|
||||
if isinstance(values, Mapping):
|
||||
for idx, val in sorted(values.items()):
|
||||
|
||||
@@ -387,7 +387,7 @@ class LookupModule(LookupBase):
|
||||
try:
|
||||
rdclass = dns.rdataclass.from_text(self.get_option("class"))
|
||||
except Exception as e:
|
||||
raise AnsibleError(f"dns lookup illegal CLASS: {e}")
|
||||
raise AnsibleError(f"dns lookup illegal CLASS: {e}") from e
|
||||
myres.retry_servfail = self.get_option("retry_servfail")
|
||||
|
||||
for t in terms:
|
||||
@@ -405,7 +405,7 @@ class LookupModule(LookupBase):
|
||||
nsaddr = dns.resolver.query(ns)[0].address
|
||||
nameservers.append(nsaddr)
|
||||
except Exception as e:
|
||||
raise AnsibleError(f"dns lookup NS: {e}")
|
||||
raise AnsibleError(f"dns lookup NS: {e}") from e
|
||||
continue
|
||||
if "=" in t:
|
||||
try:
|
||||
@@ -421,7 +421,7 @@ class LookupModule(LookupBase):
|
||||
try:
|
||||
rdclass = dns.rdataclass.from_text(arg)
|
||||
except Exception as e:
|
||||
raise AnsibleError(f"dns lookup illegal CLASS: {e}")
|
||||
raise AnsibleError(f"dns lookup illegal CLASS: {e}") from e
|
||||
elif opt == "retry_servfail":
|
||||
myres.retry_servfail = boolean(arg)
|
||||
elif opt == "fail_on_error":
|
||||
@@ -458,7 +458,7 @@ class LookupModule(LookupBase):
|
||||
except dns.exception.SyntaxError:
|
||||
pass
|
||||
except Exception as e:
|
||||
raise AnsibleError(f"dns.reversename unhandled exception {e}")
|
||||
raise AnsibleError(f"dns.reversename unhandled exception {e}") from e
|
||||
domains = reversed_domains
|
||||
|
||||
if len(domains) > 1:
|
||||
@@ -487,20 +487,20 @@ class LookupModule(LookupBase):
|
||||
ret.append(rd)
|
||||
except Exception as err:
|
||||
if fail_on_error:
|
||||
raise AnsibleError(f"Lookup failed: {err}")
|
||||
raise AnsibleError(f"Lookup failed: {err}") from err
|
||||
ret.append(str(err))
|
||||
|
||||
except dns.resolver.NXDOMAIN as err:
|
||||
if fail_on_error:
|
||||
raise AnsibleError(f"Lookup failed: {err}")
|
||||
raise AnsibleError(f"Lookup failed: {err}") from err
|
||||
if not real_empty:
|
||||
ret.append("NXDOMAIN")
|
||||
except (dns.resolver.NoAnswer, dns.resolver.Timeout, dns.resolver.NoNameservers) as err:
|
||||
if fail_on_error:
|
||||
raise AnsibleError(f"Lookup failed: {err}")
|
||||
raise AnsibleError(f"Lookup failed: {err}") from err
|
||||
if not real_empty:
|
||||
ret.append("")
|
||||
except dns.exception.DNSException as err:
|
||||
raise AnsibleError(f"dns.resolver unhandled exception {err}")
|
||||
raise AnsibleError(f"dns.resolver unhandled exception {err}") from err
|
||||
|
||||
return ret
|
||||
|
||||
@@ -105,7 +105,7 @@ class LookupModule(LookupBase):
|
||||
continue
|
||||
string = ""
|
||||
except DNSException as e:
|
||||
raise AnsibleError(f"dns.resolver unhandled exception {e}")
|
||||
raise AnsibleError(f"dns.resolver unhandled exception {e}") from e
|
||||
|
||||
ret.append("".join(string))
|
||||
|
||||
|
||||
@@ -109,8 +109,8 @@ class LookupModule(LookupBase):
|
||||
try:
|
||||
vault = SecretsVault(**vault_parameters)
|
||||
return vault
|
||||
except TypeError:
|
||||
raise AnsibleError("python-dsv-sdk==0.0.1 must be installed to use this plugin")
|
||||
except TypeError as e:
|
||||
raise AnsibleError("python-dsv-sdk==0.0.1 must be installed to use this plugin") from e
|
||||
|
||||
def run(self, terms, variables, **kwargs):
|
||||
if sdk_is_missing:
|
||||
@@ -140,5 +140,5 @@ class LookupModule(LookupBase):
|
||||
display.vvv(f"DevOps Secrets Vault GET /secrets/{path}")
|
||||
result.append(vault.get_secret_json(path))
|
||||
except SecretsVaultError as error:
|
||||
raise AnsibleError(f"DevOps Secrets Vault lookup failure: {error.message}")
|
||||
raise AnsibleError(f"DevOps Secrets Vault lookup failure: {error.message}") from error
|
||||
return result
|
||||
|
||||
@@ -167,7 +167,7 @@ def etcd3_client(client_params):
|
||||
etcd = etcd3.client(**client_params)
|
||||
etcd.status()
|
||||
except Exception as exp:
|
||||
raise AnsibleLookupError(f"Cannot connect to etcd cluster: {exp}")
|
||||
raise AnsibleLookupError(f"Cannot connect to etcd cluster: {exp}") from exp
|
||||
return etcd
|
||||
|
||||
|
||||
|
||||
@@ -116,7 +116,7 @@ class PythonJWT:
|
||||
with open(path, "rb") as pem_file:
|
||||
return jwk_from_pem(pem_file.read())
|
||||
except Exception as e:
|
||||
raise AnsibleError(f"Error while parsing key file: {e}")
|
||||
raise AnsibleError(f"Error while parsing key file: {e}") from e
|
||||
|
||||
@staticmethod
|
||||
def encode_jwt(app_id, jwk, exp=600):
|
||||
@@ -129,7 +129,7 @@ class PythonJWT:
|
||||
try:
|
||||
return jwt_instance.encode(payload, jwk, alg="RS256")
|
||||
except Exception as e:
|
||||
raise AnsibleError(f"Error while encoding jwt: {e}")
|
||||
raise AnsibleError(f"Error while encoding jwt: {e}") from e
|
||||
|
||||
|
||||
def read_key(path, private_key=None):
|
||||
@@ -143,7 +143,7 @@ def read_key(path, private_key=None):
|
||||
key_bytes = pem_file.read()
|
||||
return serialization.load_pem_private_key(key_bytes, password=None)
|
||||
except Exception as e:
|
||||
raise AnsibleError(f"Error while parsing key file: {e}")
|
||||
raise AnsibleError(f"Error while parsing key file: {e}") from e
|
||||
|
||||
|
||||
def encode_jwt(app_id, private_key_obj, exp=600):
|
||||
@@ -158,7 +158,7 @@ def encode_jwt(app_id, private_key_obj, exp=600):
|
||||
try:
|
||||
return jwt.encode(payload, private_key_obj, algorithm="RS256")
|
||||
except Exception as e:
|
||||
raise AnsibleError(f"Error while encoding jwt: {e}")
|
||||
raise AnsibleError(f"Error while encoding jwt: {e}") from e
|
||||
|
||||
|
||||
def post_request(generated_jwt, installation_id, api_base):
|
||||
@@ -178,15 +178,15 @@ def post_request(generated_jwt, installation_id, api_base):
|
||||
except Exception:
|
||||
error_body = {}
|
||||
if e.code == 404:
|
||||
raise AnsibleError("Github return error. Please confirm your installation_id value is valid")
|
||||
raise AnsibleError("Github return error. Please confirm your installation_id value is valid") from e
|
||||
elif e.code == 401:
|
||||
raise AnsibleError("Github return error. Please confirm your private key is valid")
|
||||
raise AnsibleError(f"Unexpected data returned: {e} -- {error_body}")
|
||||
raise AnsibleError("Github return error. Please confirm your private key is valid") from e
|
||||
raise AnsibleError(f"Unexpected data returned: {e} -- {error_body}") from e
|
||||
response_body = response.read()
|
||||
try:
|
||||
json_data = json.loads(response_body.decode("utf-8"))
|
||||
except json.decoder.JSONDecodeError as e:
|
||||
raise AnsibleError(f"Error while dencoding JSON respone from github: {e}")
|
||||
raise AnsibleError(f"Error while dencoding JSON respone from github: {e}") from e
|
||||
return json_data.get("token")
|
||||
|
||||
|
||||
|
||||
@@ -93,7 +93,7 @@ class LookupModule(LookupBase):
|
||||
try:
|
||||
env = lmdb.open(str(db), readonly=True)
|
||||
except Exception as e:
|
||||
raise AnsibleError(f"LMDB cannot open database {db}: {e}")
|
||||
raise AnsibleError(f"LMDB cannot open database {db}: {e}") from e
|
||||
|
||||
ret = []
|
||||
if len(terms) == 0:
|
||||
|
||||
@@ -198,13 +198,13 @@ class OnePassCLIBase(metaclass=abc.ABCMeta):
|
||||
based on the current version."""
|
||||
try:
|
||||
bin_path = get_bin_path(cls.bin)
|
||||
except ValueError:
|
||||
raise AnsibleLookupError(f"Unable to locate '{cls.bin}' command line tool")
|
||||
except ValueError as e:
|
||||
raise AnsibleLookupError(f"Unable to locate '{cls.bin}' command line tool") from e
|
||||
|
||||
try:
|
||||
b_out = subprocess.check_output([bin_path, "--version"], stderr=subprocess.PIPE)
|
||||
except subprocess.CalledProcessError as cpe:
|
||||
raise AnsibleLookupError(f"Unable to get the op version: {cpe}")
|
||||
raise AnsibleLookupError(f"Unable to get the op version: {cpe}") from cpe
|
||||
|
||||
return to_text(b_out).strip()
|
||||
|
||||
@@ -653,7 +653,7 @@ class OnePass:
|
||||
self.connect_token,
|
||||
)
|
||||
except TypeError as e:
|
||||
raise AnsibleLookupError(e)
|
||||
raise AnsibleLookupError(e) from e
|
||||
|
||||
raise AnsibleLookupError(f"op version {version} is unsupported")
|
||||
|
||||
|
||||
@@ -309,7 +309,7 @@ class LookupModule(LookupBase):
|
||||
)
|
||||
self.realpass = "pass: the standard unix password manager" in passoutput
|
||||
except subprocess.CalledProcessError as e:
|
||||
raise AnsibleError(f"exit code {e.returncode} while running {e.cmd}. Error output: {e.output}")
|
||||
raise AnsibleError(f"exit code {e.returncode} while running {e.cmd}. Error output: {e.output}") from e
|
||||
|
||||
return self.realpass
|
||||
|
||||
@@ -329,14 +329,14 @@ class LookupModule(LookupBase):
|
||||
raise AnsibleAssertionError(f"{name} not in paramvals")
|
||||
self.paramvals[name] = value
|
||||
except (ValueError, AssertionError) as e:
|
||||
raise AnsibleError(e)
|
||||
raise AnsibleError(e) from e
|
||||
# check and convert values
|
||||
try:
|
||||
for key in ["create", "returnall", "overwrite", "backup", "nosymbols"]:
|
||||
if not isinstance(self.paramvals[key], bool):
|
||||
self.paramvals[key] = boolean(self.paramvals[key])
|
||||
except (ValueError, AssertionError) as e:
|
||||
raise AnsibleError(e)
|
||||
raise AnsibleError(e) from e
|
||||
if self.paramvals["missing"] not in ["error", "warn", "create", "empty"]:
|
||||
raise AnsibleError(f"{self.paramvals['missing']} is not a valid option for missing")
|
||||
if not isinstance(self.paramvals["length"], int):
|
||||
@@ -395,7 +395,7 @@ class LookupModule(LookupBase):
|
||||
except subprocess.CalledProcessError as e:
|
||||
# 'not in password store' is the expected error if a password wasn't found
|
||||
if "not in the password store" not in e.output:
|
||||
raise AnsibleError(f"exit code {e.returncode} while running {e.cmd}. Error output: {e.output}")
|
||||
raise AnsibleError(f"exit code {e.returncode} while running {e.cmd}. Error output: {e.output}") from e
|
||||
|
||||
if self.paramvals["missing"] == "error":
|
||||
raise AnsibleError(f"passwordstore: passname {self.passname} not found and missing=error is set")
|
||||
@@ -459,7 +459,7 @@ class LookupModule(LookupBase):
|
||||
try:
|
||||
check_output2([self.pass_cmd, "insert", "-f", "-m", self.passname], input=msg, env=self.env)
|
||||
except subprocess.CalledProcessError as e:
|
||||
raise AnsibleError(f"exit code {e.returncode} while running {e.cmd}. Error output: {e.output}")
|
||||
raise AnsibleError(f"exit code {e.returncode} while running {e.cmd}. Error output: {e.output}") from e
|
||||
return newpass
|
||||
|
||||
def generate_password(self):
|
||||
@@ -480,7 +480,7 @@ class LookupModule(LookupBase):
|
||||
try:
|
||||
check_output2([self.pass_cmd, "insert", "-f", "-m", self.passname], input=msg, env=self.env)
|
||||
except subprocess.CalledProcessError as e:
|
||||
raise AnsibleError(f"exit code {e.returncode} while running {e.cmd}. Error output: {e.output}")
|
||||
raise AnsibleError(f"exit code {e.returncode} while running {e.cmd}. Error output: {e.output}") from e
|
||||
|
||||
return newpass
|
||||
|
||||
|
||||
@@ -112,5 +112,5 @@ class LookupModule(LookupBase):
|
||||
ret.append(to_text(res))
|
||||
except Exception as e:
|
||||
# connection failed or key not found
|
||||
raise AnsibleError(f"Encountered exception while fetching {term}: {e}")
|
||||
raise AnsibleError(f"Encountered exception while fetching {term}: {e}") from e
|
||||
return ret
|
||||
|
||||
@@ -98,5 +98,5 @@ class LookupModule(LookupBase):
|
||||
display.vvv(f"Secret Server lookup of Secret with ID {term}")
|
||||
result.append({term: secret_server.get_pam_secret(term)})
|
||||
except Exception as error:
|
||||
raise AnsibleError(f"Secret Server lookup failure: {error.message}")
|
||||
raise AnsibleError(f"Secret Server lookup failure: {error.message}") from error
|
||||
return result
|
||||
|
||||
@@ -74,7 +74,7 @@ class LookupModule(LookupBase):
|
||||
|
||||
except (ValueError, AssertionError) as e:
|
||||
# In case "file" or "key" are not present
|
||||
raise AnsibleError(e)
|
||||
raise AnsibleError(e) from e
|
||||
|
||||
key = paramvals["key"]
|
||||
|
||||
|
||||
@@ -377,8 +377,8 @@ class TSSClient(metaclass=abc.ABCMeta): # noqa: B024
|
||||
file_content = i["itemValue"].content
|
||||
with open(os.path.join(file_download_path, f"{obj['id']}_{i['slug']}"), "wb") as f:
|
||||
f.write(file_content)
|
||||
except ValueError:
|
||||
raise AnsibleOptionsError(f"Failed to download {i['slug']}")
|
||||
except ValueError as e:
|
||||
raise AnsibleOptionsError(f"Failed to download {i['slug']}") from e
|
||||
except AttributeError:
|
||||
display.warning(f"Could not read file content for {i['slug']}")
|
||||
finally:
|
||||
@@ -403,15 +403,15 @@ class TSSClient(metaclass=abc.ABCMeta): # noqa: B024
|
||||
def _term_to_secret_id(term):
|
||||
try:
|
||||
return int(term)
|
||||
except ValueError:
|
||||
raise AnsibleOptionsError("Secret ID must be an integer")
|
||||
except ValueError as e:
|
||||
raise AnsibleOptionsError("Secret ID must be an integer") from e
|
||||
|
||||
@staticmethod
|
||||
def _term_to_folder_id(term):
|
||||
try:
|
||||
return int(term)
|
||||
except ValueError:
|
||||
raise AnsibleOptionsError("Folder ID must be an integer")
|
||||
except ValueError as e:
|
||||
raise AnsibleOptionsError("Folder ID must be an integer") from e
|
||||
|
||||
|
||||
class TSSClientV0(TSSClient):
|
||||
@@ -493,4 +493,4 @@ class LookupModule(LookupBase):
|
||||
for term in terms
|
||||
]
|
||||
except SecretServerError as error:
|
||||
raise AnsibleError(f"Secret Server lookup failure: {error.message}")
|
||||
raise AnsibleError(f"Secret Server lookup failure: {error.message}") from error
|
||||
|
||||
Reference in New Issue
Block a user