1
0
Fork 0
mirror of https://github.com/ansible-collections/community.general.git synced 2026-02-04 07:51:50 +00:00

replace batch of redundant to_native() occurrences (#11102)

* replace batch of redundant to_native() occurrences

* add changelog frag

* Update plugins/modules/idrac_redfish_config.py

Co-authored-by: Felix Fontein <felix@fontein.de>

* reformat

* Apply suggestions from code review

Co-authored-by: Felix Fontein <felix@fontein.de>

* Update plugins/modules/dimensiondata_network.py

Co-authored-by: Felix Fontein <felix@fontein.de>

---------

Co-authored-by: Felix Fontein <felix@fontein.de>
This commit is contained in:
Alexei Znamensky 2025-11-13 09:42:19 +13:00 committed by GitHub
parent ec091060d7
commit e5ee3eb88b
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
13 changed files with 42 additions and 42 deletions

View file

@ -0,0 +1,13 @@
minor_changes:
- atomic_container - remove redundant conversions to unicode (https://github.com/ansible-collections/community.general/pull/11102).
- circonus_annotation - remove redundant conversions to unicode (https://github.com/ansible-collections/community.general/pull/11102).
- dimensiondata_network - remove redundant conversions to unicode (https://github.com/ansible-collections/community.general/pull/11102).
- idrac_redfish_config - remove redundant conversions to unicode (https://github.com/ansible-collections/community.general/pull/11102).
- jenkins_plugin - remove redundant conversions to unicode (https://github.com/ansible-collections/community.general/pull/11102).
- ldap_attrs - remove redundant conversions to unicode (https://github.com/ansible-collections/community.general/pull/11102).
- ldap_entry - remove redundant conversions to unicode (https://github.com/ansible-collections/community.general/pull/11102).
- ldap_inc - remove redundant conversions to unicode (https://github.com/ansible-collections/community.general/pull/11102).
- onepassword_info - remove redundant conversions to unicode (https://github.com/ansible-collections/community.general/pull/11102).
- sensu_subscription - remove redundant conversions to unicode (https://github.com/ansible-collections/community.general/pull/11102).
- statusio_maintenance - remove redundant conversions to unicode (https://github.com/ansible-collections/community.general/pull/11102).
- vmadm - remove redundant conversions to unicode (https://github.com/ansible-collections/community.general/pull/11102).

View file

@ -103,7 +103,6 @@ msg:
import traceback import traceback
from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.common.text.converters import to_native
def do_install(module, mode, rootfs, container, image, values_list, backend): def do_install(module, mode, rootfs, container, image, values_list, backend):
@ -227,7 +226,7 @@ def main():
try: try:
core(module) core(module)
except Exception as e: except Exception as e:
module.fail_json(msg="Unanticipated error running atomic: %s" % to_native(e), exception=traceback.format_exc()) module.fail_json(msg=f"Unanticipated error running atomic: {e}", exception=traceback.format_exc())
if __name__ == "__main__": if __name__ == "__main__":

View file

@ -160,7 +160,6 @@ except ImportError:
HAS_REQUESTS = False HAS_REQUESTS = False
from ansible.module_utils.basic import AnsibleModule, missing_required_lib from ansible.module_utils.basic import AnsibleModule, missing_required_lib
from ansible.module_utils.common.text.converters import to_native
def check_requests_dep(module): def check_requests_dep(module):
@ -235,7 +234,7 @@ def main():
try: try:
resp = post_annotation(annotation, module.params["api_key"]) resp = post_annotation(annotation, module.params["api_key"])
except requests.exceptions.RequestException as e: except requests.exceptions.RequestException as e:
module.fail_json(msg="Request Failed", reason=to_native(e), exception=traceback.format_exc()) module.fail_json(msg="Request Failed", reason=f"{e}", exception=traceback.format_exc())
module.exit_json(changed=True, annotation=resp.json()) module.exit_json(changed=True, annotation=resp.json())

View file

@ -120,7 +120,6 @@ import traceback
from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.basic import AnsibleModule
from ansible_collections.community.general.plugins.module_utils.dimensiondata import HAS_LIBCLOUD, DimensionDataModule from ansible_collections.community.general.plugins.module_utils.dimensiondata import HAS_LIBCLOUD, DimensionDataModule
from ansible.module_utils.common.text.converters import to_native
if HAS_LIBCLOUD: if HAS_LIBCLOUD:
from libcloud.compute.base import NodeLocation from libcloud.compute.base import NodeLocation
@ -223,9 +222,7 @@ class DimensionDataNetworkModule(DimensionDataModule):
self.location, self.name, self.module.params["service_plan"], description=self.description self.location, self.name, self.module.params["service_plan"], description=self.description
) )
except DimensionDataAPIException as e: except DimensionDataAPIException as e:
self.module.fail_json( self.module.fail_json(msg=f"Failed to create new network: {e}", exception=traceback.format_exc())
msg="Failed to create new network: %s" % to_native(e), exception=traceback.format_exc()
)
if self.module.params["wait"] is True: if self.module.params["wait"] is True:
network = self._wait_for_network_state(network.id, "NORMAL") network = self._wait_for_network_state(network.id, "NORMAL")
@ -245,7 +242,7 @@ class DimensionDataNetworkModule(DimensionDataModule):
self.module.fail_json("Unexpected failure deleting network with id %s" % network.id) self.module.fail_json("Unexpected failure deleting network with id %s" % network.id)
except DimensionDataAPIException as e: except DimensionDataAPIException as e:
self.module.fail_json(msg="Failed to delete network: %s" % to_native(e), exception=traceback.format_exc()) self.module.fail_json(msg=f"Failed to delete network: {e}", exception=traceback.format_exc())
def _wait_for_network_state(self, net_id, state_to_wait_for): def _wait_for_network_state(self, net_id, state_to_wait_for):
try: try:
@ -258,7 +255,7 @@ class DimensionDataNetworkModule(DimensionDataModule):
) )
except DimensionDataAPIException as e: except DimensionDataAPIException as e:
self.module.fail_json( self.module.fail_json(
msg="Network did not reach % state in time: %s" % (state_to_wait_for, to_native(e)), msg=f"Network did not reach {state_to_wait_for} state in time: {e}",
exception=traceback.format_exc(), exception=traceback.format_exc(),
) )

View file

@ -170,8 +170,7 @@ class IdracRedfishUtils(RedfishUtils):
check_required_arguments(required_arg_spec, self.module.params) check_required_arguments(required_arg_spec, self.module.params)
except TypeError as e: except TypeError as e:
msg = to_native(e) self.module.fail_json(msg=f"{e}")
self.module.fail_json(msg=msg)
key = "Attributes" key = "Attributes"
command_manager_attributes_uri_map = { command_manager_attributes_uri_map = {

View file

@ -401,7 +401,7 @@ class JenkinsPlugin:
try: try:
json_data = json.loads(to_native(r.read())) json_data = json.loads(to_native(r.read()))
except Exception as e: except Exception as e:
self.module.fail_json(msg=f"Cannot parse {what} JSON data.", details=to_native(e)) self.module.fail_json(msg=f"Cannot parse {what} JSON data.", details=f"{e}")
return json_data return json_data
@ -477,7 +477,7 @@ class JenkinsPlugin:
if dont_fail: if dont_fail:
raise FailedInstallingWithPluginManager(e) from e raise FailedInstallingWithPluginManager(e) from e
else: else:
self.module.fail_json(msg=msg_exception, details=to_native(e)) self.module.fail_json(msg=msg_exception, details=f"{e}")
return response return response
@ -695,7 +695,7 @@ class JenkinsPlugin:
except Exception as e: except Exception as e:
if os.path.exists(cache_path): if os.path.exists(cache_path):
os.remove(cache_path) os.remove(cache_path)
self.module.fail_json(msg="Failed to parse plugin-versions.json", details=to_native(e)) self.module.fail_json(msg="Failed to parse plugin-versions.json", details=f"{e}")
plugin_versions = plugin_data.get("plugins", {}).get(name) plugin_versions = plugin_data.get("plugins", {}).get(name)
if not plugin_versions: if not plugin_versions:
@ -743,7 +743,7 @@ class JenkinsPlugin:
try: try:
updates_file, download_updates = download_updates_file(self.params["updates_expiration"]) updates_file, download_updates = download_updates_file(self.params["updates_expiration"])
except OSError as e: except OSError as e:
self.module.fail_json(msg="Cannot create temporal directory.", details=to_native(e)) self.module.fail_json(msg="Cannot create temporal directory.", details=f"{e}")
# Download the updates file if needed # Download the updates file if needed
if download_updates: if download_updates:
@ -761,9 +761,7 @@ class JenkinsPlugin:
try: try:
os.close(tmp_update_fd) os.close(tmp_update_fd)
except IOError as e: except IOError as e:
self.module.fail_json( self.module.fail_json(msg=f"Cannot close the tmp updates file {tmp_updates_file}.", details=f"{e}")
msg=f"Cannot close the tmp updates file {tmp_updates_file}.", details=to_native(e)
)
else: else:
tmp_updates_file = updates_file tmp_updates_file = updates_file
@ -777,12 +775,12 @@ class JenkinsPlugin:
except IOError as e: except IOError as e:
self.module.fail_json( self.module.fail_json(
msg=f"Cannot open{' temporary' if tmp_updates_file != updates_file else ''} updates file.", msg=f"Cannot open{' temporary' if tmp_updates_file != updates_file else ''} updates file.",
details=to_native(e), details=f"{e}",
) )
except Exception as e: except Exception as e:
self.module.fail_json( self.module.fail_json(
msg=f"Cannot load JSON data from the{' temporary' if tmp_updates_file != updates_file else ''} updates file.", msg=f"Cannot load JSON data from the{' temporary' if tmp_updates_file != updates_file else ''} updates file.",
details=to_native(e), details=f"{e}",
) )
# Move the updates file to the right place if we could read it # Move the updates file to the right place if we could read it
@ -812,7 +810,7 @@ class JenkinsPlugin:
try: try:
os.close(tmp_f_fd) os.close(tmp_f_fd)
except IOError as e: except IOError as e:
self.module.fail_json(msg=f"Cannot close the temporal plugin file {tmp_f}.", details=to_native(e)) self.module.fail_json(msg=f"Cannot close the temporal plugin file {tmp_f}.", details=f"{e}")
# Move the file onto the right place # Move the file onto the right place
self.module.atomic_move(os.path.abspath(tmp_f), os.path.abspath(f)) self.module.atomic_move(os.path.abspath(tmp_f), os.path.abspath(f))
@ -923,7 +921,7 @@ def main():
try: try:
module.params["timeout"] = float(module.params["timeout"]) module.params["timeout"] = float(module.params["timeout"])
except ValueError as e: except ValueError as e:
module.fail_json(msg=f"Cannot convert {module.params['timeout']} to float.", details=to_native(e)) module.fail_json(msg=f"Cannot convert {module.params['timeout']} to float.", details=f"{e}")
# Instantiate the JenkinsPlugin object # Instantiate the JenkinsPlugin object
jp = JenkinsPlugin(module) jp = JenkinsPlugin(module)

View file

@ -160,7 +160,7 @@ modlist:
import traceback import traceback
from ansible.module_utils.basic import AnsibleModule, missing_required_lib from ansible.module_utils.basic import AnsibleModule, missing_required_lib
from ansible.module_utils.common.text.converters import to_native, to_bytes, to_text from ansible.module_utils.common.text.converters import to_bytes, to_text
from ansible_collections.community.general.plugins.module_utils.ldap import ( from ansible_collections.community.general.plugins.module_utils.ldap import (
LdapGeneric, LdapGeneric,
gen_specs, gen_specs,
@ -327,7 +327,7 @@ def main():
try: try:
ldap.connection.modify_s(ldap.dn, modlist) ldap.connection.modify_s(ldap.dn, modlist)
except Exception as e: except Exception as e:
module.fail_json(msg="Attribute action failed.", details=to_native(e)) module.fail_json(msg="Attribute action failed.", details=f"{e}")
module.exit_json(changed=changed, modlist=modlist, diff={"before": old_attrs, "after": new_attrs}) module.exit_json(changed=changed, modlist=modlist, diff={"before": old_attrs, "after": new_attrs})

View file

@ -132,7 +132,7 @@ RETURN = r"""
import traceback import traceback
from ansible.module_utils.basic import AnsibleModule, missing_required_lib from ansible.module_utils.basic import AnsibleModule, missing_required_lib
from ansible.module_utils.common.text.converters import to_native, to_bytes from ansible.module_utils.common.text.converters import to_bytes
from ansible_collections.community.general.plugins.module_utils.ldap import ( from ansible_collections.community.general.plugins.module_utils.ldap import (
LdapGeneric, LdapGeneric,
gen_specs, gen_specs,
@ -264,7 +264,7 @@ def main():
try: try:
action() action()
except Exception as e: except Exception as e:
module.fail_json(msg="Entry action failed.", details=to_native(e), exception=traceback.format_exc()) module.fail_json(msg="Entry action failed.", details=f"{e}", exception=traceback.format_exc())
module.exit_json(changed=(action is not None)) module.exit_json(changed=(action is not None))

View file

@ -115,7 +115,7 @@ rfc4525:
""" """
from ansible.module_utils.basic import AnsibleModule, missing_required_lib from ansible.module_utils.basic import AnsibleModule, missing_required_lib
from ansible.module_utils.common.text.converters import to_native, to_bytes from ansible.module_utils.common.text.converters import to_bytes
from ansible_collections.community.general.plugins.module_utils import deps from ansible_collections.community.general.plugins.module_utils import deps
from ansible_collections.community.general.plugins.module_utils.ldap import ( from ansible_collections.community.general.plugins.module_utils.ldap import (
LdapGeneric, LdapGeneric,
@ -222,7 +222,7 @@ def main():
module.fail_json(msg="The entry does not exist or does not contain the specified attribute.") module.fail_json(msg="The entry does not exist or does not contain the specified attribute.")
except Exception as e: except Exception as e:
module.fail_json(msg="Attribute action failed.", details=to_native(e)) module.fail_json(msg="Attribute action failed.", details=f"{e}")
module.exit_json(changed=changed, incremented=changed, attribute=mod.attr, value=ret, rfc4525=rfc4525) module.exit_json(changed=changed, incremented=changed, attribute=mod.attr, value=ret, rfc4525=rfc4525)

View file

@ -266,7 +266,7 @@ class OnePasswordInfo:
return output return output
except Exception as e: except Exception as e:
if re.search(".*not found.*", to_native(e)): if re.search(".*not found.*", f"{e}"):
module.fail_json(msg=f"Unable to find an item in 1Password named '{item_id}'.") module.fail_json(msg=f"Unable to find an item in 1Password named '{item_id}'.")
else: else:
module.fail_json(msg=f"Unexpected error attempting to find an item in 1Password named '{item_id}': {e}") module.fail_json(msg=f"Unexpected error attempting to find an item in 1Password named '{item_id}': {e}")

View file

@ -72,7 +72,6 @@ import json
import traceback import traceback
from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.common.text.converters import to_native
def sensu_subscription(module, path, name, state="present", backup=False): def sensu_subscription(module, path, name, state="present", backup=False):
@ -128,9 +127,7 @@ def sensu_subscription(module, path, name, state="present", backup=False):
try: try:
open(path, "w").write(json.dumps(config, indent=2) + "\n") open(path, "w").write(json.dumps(config, indent=2) + "\n")
except IOError as e: except IOError as e:
module.fail_json( module.fail_json(msg=f"Failed to write to file {path}: {e}", exception=traceback.format_exc())
msg="Failed to write to file %s: %s" % (path, to_native(e)), exception=traceback.format_exc()
)
return changed, reasons return changed, reasons

View file

@ -178,7 +178,6 @@ import datetime
import json import json
from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.common.text.converters import to_native
from ansible.module_utils.urls import open_url from ansible.module_utils.urls import open_url
from ansible_collections.community.general.plugins.module_utils.datetime import ( from ansible_collections.community.general.plugins.module_utils.datetime import (
@ -198,7 +197,7 @@ def get_api_auth_headers(api_id, api_key, url, statuspage):
auth_headers = headers auth_headers = headers
auth_content = data auth_content = data
except Exception as e: except Exception as e:
return 1, None, None, to_native(e) return 1, None, None, f"{e}"
return 0, auth_headers, auth_content, None return 0, auth_headers, auth_content, None
@ -310,7 +309,7 @@ def create_maintenance(
if data["status"]["error"] == "yes": if data["status"]["error"] == "yes":
return 1, None, data["status"]["message"] return 1, None, data["status"]["message"]
except Exception as e: except Exception as e:
return 1, None, to_native(e) return 1, None, f"{e}"
return 0, None, None return 0, None, None
@ -327,7 +326,7 @@ def delete_maintenance(auth_headers, url, statuspage, maintenance_id):
if data["status"]["error"] == "yes": if data["status"]["error"] == "yes":
return 1, None, "Invalid maintenance_id" return 1, None, "Invalid maintenance_id"
except Exception as e: except Exception as e:
return 1, None, to_native(e) return 1, None, f"{e}"
return 0, None, None return 0, None, None

View file

@ -346,7 +346,6 @@ import traceback
from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.common.text.converters import to_native
# While vmadm(1M) supports a -E option to return any errors in JSON, the # While vmadm(1M) supports a -E option to return any errors in JSON, the
# generated JSON does not play well with the JSON parsers of Python. # generated JSON does not play well with the JSON parsers of Python.
@ -369,7 +368,7 @@ def get_vm_prop(module, uuid, prop):
except Exception as e: except Exception as e:
module.fail_json( module.fail_json(
msg=f"Invalid JSON returned by vmadm for uuid lookup of {prop}", msg=f"Invalid JSON returned by vmadm for uuid lookup of {prop}",
details=to_native(e), details=f"{e}",
exception=traceback.format_exc(), exception=traceback.format_exc(),
) )
@ -395,7 +394,7 @@ def get_vm_uuid(module, alias):
except Exception as e: except Exception as e:
module.fail_json( module.fail_json(
msg=f"Invalid JSON returned by vmadm for uuid lookup of {alias}", msg=f"Invalid JSON returned by vmadm for uuid lookup of {alias}",
details=to_native(e), details=f"{e}",
exception=traceback.format_exc(), exception=traceback.format_exc(),
) )
@ -416,7 +415,7 @@ def get_all_vm_uuids(module):
stdout_json = json.loads(stdout) stdout_json = json.loads(stdout)
return [v["uuid"] for v in stdout_json] return [v["uuid"] for v in stdout_json]
except Exception as e: except Exception as e:
module.fail_json(msg="Could not retrieve VM UUIDs", details=to_native(e), exception=traceback.format_exc()) module.fail_json(msg="Could not retrieve VM UUIDs", details=f"{e}", exception=traceback.format_exc())
def new_vm(module, uuid, vm_state): def new_vm(module, uuid, vm_state):