From 6bd0fbb63c48ce5121c8c2ad64f58b35811e4f89 Mon Sep 17 00:00:00 2001 From: Abhijeet Kasurde Date: Tue, 26 Dec 2017 08:33:21 +0530 Subject: [PATCH] Remove deprecated get_exception API Signed-off-by: Abhijeet Kasurde --- lib/ansible/modules/files/acl.py | 8 +- lib/ansible/modules/files/xattr.py | 8 +- .../modules/network/aos/aos_blueprint.py | 8 +- .../network/aos/aos_blueprint_param.py | 14 ++-- .../network/aos/aos_blueprint_virtnet.py | 13 ++-- .../modules/network/eos/eos_command.py | 7 +- .../network/fortios/fortios_address.py | 2 +- .../modules/network/junos/junos_facts.py | 8 +- .../modules/network/junos/junos_package.py | 7 +- .../network/panos/_panos_nat_policy.py | 7 +- .../network/panos/_panos_security_policy.py | 7 +- .../network/panos/panos_cert_gen_ssh.py | 8 +- .../modules/network/panos/panos_import.py | 8 +- .../modules/network/panos/panos_interface.py | 9 +-- .../modules/network/panos/panos_mgtconfig.py | 8 +- .../modules/network/panos/panos_nat_rule.py | 17 ++--- .../modules/network/panos/panos_object.py | 17 ++--- lib/ansible/modules/network/panos/panos_pg.py | 7 +- .../modules/network/panos/panos_sag.py | 14 ++-- .../network/panos/panos_security_rule.py | 17 ++--- .../modules/network/vyos/vyos_command.py | 7 +- lib/ansible/modules/packaging/os/apt.py | 14 ++-- .../modules/packaging/os/apt_repository.py | 24 +++--- .../modules/packaging/os/yum_repository.py | 17 ++--- .../modules/storage/netapp/netapp_e_host.py | 42 +++++------ .../storage/netapp/netapp_e_lun_mapping.py | 17 ++--- .../storage/netapp/netapp_e_snapshot_group.py | 35 ++++----- .../netapp/netapp_e_snapshot_images.py | 13 ++-- .../netapp/netapp_e_snapshot_volume.py | 4 +- .../storage/netapp/netapp_e_storage_system.py | 25 +++---- .../storage/netapp/netapp_e_storagepool.py | 75 +++++++------------ .../modules/storage/netapp/netapp_e_volume.py | 59 ++++++--------- .../storage/netapp/netapp_e_volume_copy.py | 7 +- .../storage/netapp/sf_volume_manager.py | 18 ++--- lib/ansible/modules/system/known_hosts.py | 19 ++--- lib/ansible/modules/system/locale_gen.py | 6 +- lib/ansible/modules/system/mount.py | 11 +-- lib/ansible/modules/system/pamd.py | 8 +- lib/ansible/modules/system/user.py | 41 ++++------ .../modules/web_infrastructure/htpasswd.py | 12 +-- .../web_infrastructure/jenkins_plugin.py | 34 +++------ .../modules/web_infrastructure/taiga_issue.py | 11 +-- 42 files changed, 284 insertions(+), 409 deletions(-) diff --git a/lib/ansible/modules/files/acl.py b/lib/ansible/modules/files/acl.py index 7267bf15d4a..d2441a02186 100644 --- a/lib/ansible/modules/files/acl.py +++ b/lib/ansible/modules/files/acl.py @@ -130,7 +130,7 @@ acl: import os from ansible.module_utils.basic import AnsibleModule, get_platform -from ansible.module_utils.pycompat24 import get_exception +from ansible.module_utils._text import to_native def split_entry(entry): @@ -225,9 +225,8 @@ def run_acl(module, cmd, check_rc=True): try: (rc, out, err) = module.run_command(' '.join(cmd), check_rc=check_rc) - except Exception: - e = get_exception() - module.fail_json(msg=e.strerror) + except Exception as e: + module.fail_json(msg=to_native(e)) lines = [] for l in out.splitlines(): @@ -355,5 +354,6 @@ def main(): module.exit_json(changed=changed, msg=msg, acl=acl) + if __name__ == '__main__': main() diff --git a/lib/ansible/modules/files/xattr.py b/lib/ansible/modules/files/xattr.py index 1c0f8aef316..000ddd0a296 100644 --- a/lib/ansible/modules/files/xattr.py +++ b/lib/ansible/modules/files/xattr.py @@ -77,7 +77,7 @@ import re # import module snippets from ansible.module_utils.basic import AnsibleModule -from ansible.module_utils.pycompat24 import get_exception +from ansible.module_utils._text import to_native def get_xattr_keys(module, path, follow): @@ -134,9 +134,8 @@ def _run_xattr(module, cmd, check_rc=True): try: (rc, out, err) = module.run_command(' '.join(cmd), check_rc=check_rc) - except Exception: - e = get_exception() - module.fail_json(msg="%s!" % e.strerror) + except Exception as e: + module.fail_json(msg="%s!" % to_native(e)) # result = {'raw': out} result = {} @@ -210,5 +209,6 @@ def main(): module.exit_json(changed=changed, msg=msg, xattr=res) + if __name__ == '__main__': main() diff --git a/lib/ansible/modules/network/aos/aos_blueprint.py b/lib/ansible/modules/network/aos/aos_blueprint.py index df74271854a..387e59308a0 100644 --- a/lib/ansible/modules/network/aos/aos_blueprint.py +++ b/lib/ansible/modules/network/aos/aos_blueprint.py @@ -134,7 +134,6 @@ build_errors: from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.network.aos.aos import get_aos_session, check_aos_version, find_collection_item -from ansible.module_utils.pycompat24 import get_exception def create_blueprint(module, aos, name): @@ -149,8 +148,7 @@ def create_blueprint(module, aos, name): blueprint = aos.Blueprints[name] blueprint.create(template_id, reference_arch=margs['reference_arch']) - except: - exc = get_exception() + except Exception as exc: msg = "Unable to create blueprint: %s" % exc.message if 'UNPROCESSABLE ENTITY' in exc.message: msg += ' (likely missing dependencies)' @@ -170,8 +168,7 @@ def ensure_absent(module, aos, blueprint): if not module.check_mode: try: blueprint.delete() - except: - exc = get_exception() + except Exception as exc: module.fail_json(msg='Unable to delete blueprint, %s' % exc.message) module.exit_json(changed=True, @@ -294,5 +291,6 @@ def main(): aos_blueprint(module) + if __name__ == '__main__': main() diff --git a/lib/ansible/modules/network/aos/aos_blueprint_param.py b/lib/ansible/modules/network/aos/aos_blueprint_param.py index e5d1bd0b42b..e6a31ed9c53 100644 --- a/lib/ansible/modules/network/aos/aos_blueprint_param.py +++ b/lib/ansible/modules/network/aos/aos_blueprint_param.py @@ -163,7 +163,7 @@ import json from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.network.aos.aos import get_aos_session, find_collection_item, check_aos_version -from ansible.module_utils.pycompat24 import get_exception +from ansible.module_utils._text import to_native try: import yaml @@ -238,10 +238,9 @@ def blueprint_param_present(module, aos, blueprint, param, param_value): if not module.check_mode: try: param.value = param_value - except: - exc = get_exception() - module.fail_json(msg='unable to write to param %s: %r' % - (margs['name'], exc)) + except Exception as exc: + module.fail_json(msg='unable to write to param %s: %s' % + (margs['name'], to_native(exc))) module.exit_json(changed=True, blueprint=blueprint.name, @@ -265,9 +264,8 @@ def blueprint_param_absent(module, aos, blueprint, param, param_value): if not module.check_mode: try: param.value = {} - except: - exc = get_exception() - module.fail_json(msg='Unable to write to param %s: %r' % (margs['name'], exc)) + except Exception as exc: + module.fail_json(msg='Unable to write to param %s: %s' % (margs['name'], to_native(exc))) module.exit_json(changed=True, blueprint=blueprint.name, diff --git a/lib/ansible/modules/network/aos/aos_blueprint_virtnet.py b/lib/ansible/modules/network/aos/aos_blueprint_virtnet.py index 62937efbcad..abdb1aea505 100644 --- a/lib/ansible/modules/network/aos/aos_blueprint_virtnet.py +++ b/lib/ansible/modules/network/aos/aos_blueprint_virtnet.py @@ -84,8 +84,8 @@ EXAMPLES = ''' import json -from ansible.module_utils.pycompat24 import get_exception from ansible.module_utils.basic import AnsibleModule +from ansible.module_utils._text import to_native from ansible.module_utils.network.aos.aos import get_aos_session, find_collection_item, do_load_resource, check_aos_version, content_to_dict @@ -103,9 +103,8 @@ def ensure_present(module, aos, blueprint, virtnet): if not module.check_mode: try: virtnet.create(module.params['content']) - except: - e = get_exception() - module.fail_json(msg="unable to create virtual-network : %r" % e) + except Exception as e: + module.fail_json(msg="unable to create virtual-network : %s" % to_native(e)) module.exit_json(changed=True, blueprint=blueprint.name, @@ -120,9 +119,8 @@ def ensure_absent(module, aos, blueprint, virtnet): if not module.check_mode: try: virtnet.delete() - except: - e = get_exception() - module.fail_json(msg="unable to delete virtual-network %s : %r" % (virtnet.name, e)) + except Exception as e: + module.fail_json(msg="unable to delete virtual-network %s : %s" % (virtnet.name, to_native(e))) module.exit_json(changed=True, blueprint=blueprint.name) @@ -214,5 +212,6 @@ def main(): blueprint_virtnet(module) + if __name__ == '__main__': main() diff --git a/lib/ansible/modules/network/eos/eos_command.py b/lib/ansible/modules/network/eos/eos_command.py index 7d4c4cd18b2..cfccb94b364 100644 --- a/lib/ansible/modules/network/eos/eos_command.py +++ b/lib/ansible/modules/network/eos/eos_command.py @@ -137,7 +137,7 @@ failed_conditions: import time from ansible.module_utils.basic import AnsibleModule -from ansible.module_utils.pycompat24 import get_exception +from ansible.module_utils._text import to_native from ansible.module_utils.six import string_types from ansible.module_utils.network.common.parsing import Conditional from ansible.module_utils.network.common.utils import ComplexList @@ -216,9 +216,8 @@ def main(): try: conditionals = [Conditional(c) for c in wait_for] - except AttributeError: - exc = get_exception() - module.fail_json(msg=str(exc)) + except AttributeError as exc: + module.fail_json(msg=to_native(exc)) retries = module.params['retries'] interval = module.params['interval'] diff --git a/lib/ansible/modules/network/fortios/fortios_address.py b/lib/ansible/modules/network/fortios/fortios_address.py index f8692306245..dc9cc5965ad 100644 --- a/lib/ansible/modules/network/fortios/fortios_address.py +++ b/lib/ansible/modules/network/fortios/fortios_address.py @@ -110,7 +110,6 @@ from ansible.module_utils.network.fortios.fortios import fortios_argument_spec, from ansible.module_utils.network.fortios.fortios import backup, AnsibleFortios from ansible.module_utils.basic import AnsibleModule -from ansible.module_utils.pycompat24 import get_exception # check for netaddr lib @@ -287,5 +286,6 @@ def main(): # Apply changes (check mode is managed directly by the fortigate object) fortigate.apply_changes() + if __name__ == '__main__': main() diff --git a/lib/ansible/modules/network/junos/junos_facts.py b/lib/ansible/modules/network/junos/junos_facts.py index 7992c4d831d..62aab0b9c45 100644 --- a/lib/ansible/modules/network/junos/junos_facts.py +++ b/lib/ansible/modules/network/junos/junos_facts.py @@ -81,7 +81,7 @@ from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.network.common.netconf import exec_rpc from ansible.module_utils.network.junos.junos import junos_argument_spec, get_param from ansible.module_utils.network.junos.junos import get_configuration, get_connection -from ansible.module_utils.pycompat24 import get_exception +from ansible.module_utils._text import to_native from ansible.module_utils.six import iteritems @@ -263,9 +263,8 @@ class Facts(FactsBase): device = Device(host, **kwargs) device.open() device.timeout = get_param(module, 'timeout') or 10 - except ConnectError: - exc = get_exception() - module.fail_json('unable to connect to %s: %s' % (host, str(exc))) + except ConnectError as exc: + module.fail_json('unable to connect to %s: %s' % (host, to_native(exc))) return device @@ -286,6 +285,7 @@ class Facts(FactsBase): return facts + FACT_SUBSETS = dict( default=Default, hardware=Hardware, diff --git a/lib/ansible/modules/network/junos/junos_package.py b/lib/ansible/modules/network/junos/junos_package.py index daead2d90bd..fcaae78ad92 100644 --- a/lib/ansible/modules/network/junos/junos_package.py +++ b/lib/ansible/modules/network/junos/junos_package.py @@ -103,7 +103,7 @@ EXAMPLES = """ """ from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.network.junos.junos import junos_argument_spec, get_param -from ansible.module_utils.pycompat24 import get_exception +from ansible.module_utils._text import to_native try: from jnpr.junos import Device @@ -134,9 +134,8 @@ def connect(module): device = Device(host, **kwargs) device.open() device.timeout = get_param(module, 'timeout') or 10 - except ConnectError: - exc = get_exception() - module.fail_json(msg='unable to connect to %s: %s' % (host, str(exc))) + except ConnectError as exc: + module.fail_json(msg='unable to connect to %s: %s' % (host, to_native(exc))) return device diff --git a/lib/ansible/modules/network/panos/_panos_nat_policy.py b/lib/ansible/modules/network/panos/_panos_nat_policy.py index 7f7012383ea..c05869ccecb 100644 --- a/lib/ansible/modules/network/panos/_panos_nat_policy.py +++ b/lib/ansible/modules/network/panos/_panos_nat_policy.py @@ -150,7 +150,7 @@ RETURN = ''' ''' from ansible.module_utils.basic import AnsibleModule -from ansible.module_utils.basic import get_exception +from ansible.module_utils._text import to_native try: import pan.xapi @@ -345,9 +345,8 @@ def main(): module.exit_json(changed=changed, msg="okey dokey") - except PanXapiError: - exc = get_exception() - module.fail_json(msg=exc.message) + except PanXapiError as exc: + module.fail_json(msg=to_native(exc)) if __name__ == '__main__': diff --git a/lib/ansible/modules/network/panos/_panos_security_policy.py b/lib/ansible/modules/network/panos/_panos_security_policy.py index 68f5eb48d78..82e4951d322 100644 --- a/lib/ansible/modules/network/panos/_panos_security_policy.py +++ b/lib/ansible/modules/network/panos/_panos_security_policy.py @@ -260,7 +260,7 @@ RETURN = ''' ''' from ansible.module_utils.basic import AnsibleModule -from ansible.module_utils.basic import get_exception +from ansible.module_utils._text import to_native try: import pan.xapi @@ -508,9 +508,8 @@ def main(): module.fail_json(msg='Rule with the same name but different objects exists.') try: changed = add_security_rule(device, sec_rule, rule_exist) - except PanXapiError: - exc = get_exception() - module.fail_json(msg=exc.message) + except PanXapiError as exc: + module.fail_json(msg=to_native(exc)) if changed and commit: result = _commit(device, devicegroup) diff --git a/lib/ansible/modules/network/panos/panos_cert_gen_ssh.py b/lib/ansible/modules/network/panos/panos_cert_gen_ssh.py index 7c2516f9c1d..992317ddc81 100644 --- a/lib/ansible/modules/network/panos/panos_cert_gen_ssh.py +++ b/lib/ansible/modules/network/panos/panos_cert_gen_ssh.py @@ -91,7 +91,7 @@ ANSIBLE_METADATA = {'metadata_version': '1.1', from ansible.module_utils.basic import AnsibleModule -from ansible.module_utils.basic import get_exception +from ansible.module_utils._text import to_native import time try: @@ -193,11 +193,11 @@ def main(): cert_friendly_name, signed_by, rsa_nbits) - except Exception: - exc = get_exception() - module.fail_json(msg=exc.message) + except Exception as exc: + module.fail_json(msg=to_native(exc)) module.exit_json(changed=True, msg="okey dokey") + if __name__ == '__main__': main() diff --git a/lib/ansible/modules/network/panos/panos_import.py b/lib/ansible/modules/network/panos/panos_import.py index db4e523fd81..6d1df87b428 100644 --- a/lib/ansible/modules/network/panos/panos_import.py +++ b/lib/ansible/modules/network/panos/panos_import.py @@ -83,7 +83,7 @@ ANSIBLE_METADATA = {'metadata_version': '1.1', from ansible.module_utils.basic import AnsibleModule -from ansible.module_utils.basic import get_exception +from ansible.module_utils._text import to_native import os.path import xml.etree @@ -183,9 +183,8 @@ def main(): try: changed, filename = import_file(xapi, module, ip_address, file_, category) - except Exception: - exc = get_exception() - module.fail_json(msg=exc.message) + except Exception as exc: + module.fail_json(msg=to_native(exc)) # cleanup and delete file if local if url is not None: @@ -193,5 +192,6 @@ def main(): module.exit_json(changed=changed, filename=filename, msg="okey dokey") + if __name__ == '__main__': main() diff --git a/lib/ansible/modules/network/panos/panos_interface.py b/lib/ansible/modules/network/panos/panos_interface.py index 4aea9f13909..01d916467d0 100644 --- a/lib/ansible/modules/network/panos/panos_interface.py +++ b/lib/ansible/modules/network/panos/panos_interface.py @@ -83,8 +83,7 @@ RETURN = ''' ''' from ansible.module_utils.basic import AnsibleModule -from ansible.module_utils.basic import get_exception - +from ansible.module_utils._text import to_native try: import pan.xapi @@ -171,14 +170,14 @@ def main(): try: changed = add_dhcp_if(xapi, if_name, zone_name, create_default_route) - except PanXapiError: - exc = get_exception() - module.fail_json(msg=exc.message) + except PanXapiError as exc: + module.fail_json(msg=to_native(exc)) if changed and commit: xapi.commit(cmd="", sync=True, interval=1) module.exit_json(changed=changed, msg="okey dokey") + if __name__ == '__main__': main() diff --git a/lib/ansible/modules/network/panos/panos_mgtconfig.py b/lib/ansible/modules/network/panos/panos_mgtconfig.py index fde5b640d23..427cb1d48ab 100644 --- a/lib/ansible/modules/network/panos/panos_mgtconfig.py +++ b/lib/ansible/modules/network/panos/panos_mgtconfig.py @@ -91,7 +91,7 @@ ANSIBLE_METADATA = {'metadata_version': '1.1', from ansible.module_utils.basic import AnsibleModule -from ansible.module_utils.basic import get_exception +from ansible.module_utils._text import to_native try: import pan.xapi @@ -196,11 +196,11 @@ def main(): if changed and commit: xapi.commit(cmd="", sync=True, interval=1) - except PanXapiError: - exc = get_exception() - module.fail_json(msg=exc.message) + except PanXapiError as exc: + module.fail_json(msg=to_native(exc)) module.exit_json(changed=changed, msg="okey dokey") + if __name__ == '__main__': main() diff --git a/lib/ansible/modules/network/panos/panos_nat_rule.py b/lib/ansible/modules/network/panos/panos_nat_rule.py index 588e188a69c..c723064d89f 100644 --- a/lib/ansible/modules/network/panos/panos_nat_rule.py +++ b/lib/ansible/modules/network/panos/panos_nat_rule.py @@ -149,7 +149,7 @@ ANSIBLE_METADATA = {'metadata_version': '1.1', # import pydevd # pydevd.settrace('localhost', port=60374, stdoutToServer=True, stderrToServer=True) from ansible.module_utils.basic import AnsibleModule -from ansible.module_utils.basic import get_exception +from ansible.module_utils._text import to_native try: import pan.xapi @@ -374,9 +374,8 @@ def main(): match.delete() if commit: device.commit(sync=True) - except PanXapiError: - exc = get_exception() - module.fail_json(msg=exc.message) + except PanXapiError as exc: + module.fail_json(msg=to_native(exc)) module.exit_json(changed=True, msg='Rule \'%s\' successfully deleted.' % rule_name) else: @@ -417,9 +416,8 @@ def main(): changed = add_rule(rulebase, new_rule) if changed and commit: device.commit(sync=True) - except PanXapiError: - exc = get_exception() - module.fail_json(msg=exc.message) + except PanXapiError as exc: + module.fail_json(msg=to_native(exc)) module.exit_json(changed=changed, msg='Rule \'%s\' successfully added.' % rule_name) elif operation == 'update': # Search for the rule. Update if found. @@ -450,9 +448,8 @@ def main(): changed = update_rule(rulebase, new_rule) if changed and commit: device.commit(sync=True) - except PanXapiError: - exc = get_exception() - module.fail_json(msg=exc.message) + except PanXapiError as exc: + module.fail_json(msg=to_native(exc)) module.exit_json(changed=changed, msg='Rule \'%s\' successfully updated.' % rule_name) else: module.fail_json(msg='Rule \'%s\' does not exist. Use operation: \'add\' to add it.' % rule_name) diff --git a/lib/ansible/modules/network/panos/panos_object.py b/lib/ansible/modules/network/panos/panos_object.py index 2de67c268ef..029dabac259 100644 --- a/lib/ansible/modules/network/panos/panos_object.py +++ b/lib/ansible/modules/network/panos/panos_object.py @@ -167,7 +167,7 @@ RETURN = ''' ''' from ansible.module_utils.basic import AnsibleModule -from ansible.module_utils.basic import get_exception +from ansible.module_utils._text import to_native try: import pan.xapi @@ -392,9 +392,8 @@ def main(): if match: try: match.delete() - except PanXapiError: - exc = get_exception() - module.fail_json(msg=exc.message) + except PanXapiError as exc: + module.fail_json(msg=to_native(exc)) module.exit_json(changed=True, msg='Object \'%s\' successfully deleted' % obj_name) else: @@ -424,9 +423,8 @@ def main(): color=color ) changed = add_object(device, dev_group, new_object) - except PanXapiError: - exc = get_exception() - module.fail_json(msg=exc.message) + except PanXapiError as exc: + module.fail_json(msg=to_native(exc)) module.exit_json(changed=changed, msg='Object \'%s\' successfully added' % obj_name) elif operation == "update": # Search for the object. Update if found. @@ -451,9 +449,8 @@ def main(): color=color ) changed = add_object(device, dev_group, new_object) - except PanXapiError: - exc = get_exception() - module.fail_json(msg=exc.message) + except PanXapiError as exc: + module.fail_json(msg=to_native(exc)) module.exit_json(changed=changed, msg='Object \'%s\' successfully updated.' % obj_name) else: module.fail_json(msg='Object \'%s\' does not exist. Use operation: \'add\' to add it.' % obj_name) diff --git a/lib/ansible/modules/network/panos/panos_pg.py b/lib/ansible/modules/network/panos/panos_pg.py index 555d1f38c00..8b8f4b0cd56 100644 --- a/lib/ansible/modules/network/panos/panos_pg.py +++ b/lib/ansible/modules/network/panos/panos_pg.py @@ -111,7 +111,7 @@ ANSIBLE_METADATA = {'metadata_version': '1.1', from ansible.module_utils.basic import AnsibleModule -from ansible.module_utils.basic import get_exception +from ansible.module_utils._text import to_native try: @@ -214,9 +214,8 @@ def main(): if changed and commit: xapi.commit(cmd="", sync=True, interval=1) - except PanXapiError: - exc = get_exception() - module.fail_json(msg=exc.message) + except PanXapiError as exc: + module.fail_json(msg=to_native(exc)) module.exit_json(changed=changed, msg="okey dokey") diff --git a/lib/ansible/modules/network/panos/panos_sag.py b/lib/ansible/modules/network/panos/panos_sag.py index f50c9eb824d..e5b468d8064 100755 --- a/lib/ansible/modules/network/panos/panos_sag.py +++ b/lib/ansible/modules/network/panos/panos_sag.py @@ -107,7 +107,8 @@ ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['preview'], 'supported_by': 'community'} -from ansible.module_utils.basic import AnsibleModule, get_exception +from ansible.module_utils.basic import AnsibleModule +from ansible.module_utils._text import to_native try: from pandevice import base @@ -183,8 +184,7 @@ def add_address_group(device, dev_group, ag_object): exc = None try: ag_object.create() - except Exception: - exc = get_exception() + except Exception as exc: return False, exc return True, exc @@ -204,8 +204,7 @@ def delete_address_group(device, dev_group, obj_name): if static_obj: try: static_obj.delete() - except Exception: - exc = get_exception() + except Exception as exc: return False, exc return True, None else: @@ -263,9 +262,8 @@ def main(): if result and commit: try: device.commit(sync=True) - except Exception: - exc = get_exception() - module.fail_json(msg=exc.message) + except Exception as exc: + module.fail_json(msg=to_native(exc)) elif operation == 'delete': obj_name = module.params.get('sag_name', None) diff --git a/lib/ansible/modules/network/panos/panos_security_rule.py b/lib/ansible/modules/network/panos/panos_security_rule.py index 84f1443f8c8..e53a6a5aeb5 100755 --- a/lib/ansible/modules/network/panos/panos_security_rule.py +++ b/lib/ansible/modules/network/panos/panos_security_rule.py @@ -236,7 +236,7 @@ RETURN = ''' ''' from ansible.module_utils.basic import AnsibleModule -from ansible.module_utils.basic import get_exception +from ansible.module_utils._text import to_native try: import pan.xapi @@ -479,9 +479,8 @@ def main(): try: if commit: match.delete() - except PanXapiError: - exc = get_exception() - module.fail_json(msg=exc.message) + except PanXapiError as exc: + module.fail_json(msg=to_native(exc)) module.exit_json(changed=True, msg='Rule \'%s\' successfully deleted' % rule_name) else: @@ -525,9 +524,8 @@ def main(): changed = add_rule(rulebase, new_rule) if changed and commit: device.commit(sync=True) - except PanXapiError: - exc = get_exception() - module.fail_json(msg=exc.message) + except PanXapiError as exc: + module.fail_json(msg=to_native(exc)) module.exit_json(changed=changed, msg='Rule \'%s\' successfully added' % rule_name) elif operation == 'update': # Search for the rule. Update if found. @@ -563,9 +561,8 @@ def main(): changed = update_rule(rulebase, new_rule) if changed and commit: device.commit(sync=True) - except PanXapiError: - exc = get_exception() - module.fail_json(msg=exc.message) + except PanXapiError as exc: + module.fail_json(msg=to_native(exc)) module.exit_json(changed=changed, msg='Rule \'%s\' successfully updated' % rule_name) else: module.fail_json(msg='Rule \'%s\' does not exist. Use operation: \'add\' to add it.' % rule_name) diff --git a/lib/ansible/modules/network/vyos/vyos_command.py b/lib/ansible/modules/network/vyos/vyos_command.py index 55d02fce069..3aadc295abe 100644 --- a/lib/ansible/modules/network/vyos/vyos_command.py +++ b/lib/ansible/modules/network/vyos/vyos_command.py @@ -144,7 +144,7 @@ warnings: import time from ansible.module_utils.basic import AnsibleModule -from ansible.module_utils.pycompat24 import get_exception +from ansible.module_utils._text import to_native from ansible.module_utils.network.common.parsing import Conditional from ansible.module_utils.network.common.utils import ComplexList from ansible.module_utils.six import string_types @@ -200,9 +200,8 @@ def main(): wait_for = module.params['wait_for'] or list() try: conditionals = [Conditional(c) for c in wait_for] - except AttributeError: - exc = get_exception() - module.fail_json(msg=str(exc)) + except AttributeError as exc: + module.fail_json(msg=to_native(exc)) retries = module.params['retries'] interval = module.params['interval'] diff --git a/lib/ansible/modules/packaging/os/apt.py b/lib/ansible/modules/packaging/os/apt.py index 0f57c8e5597..b865c4921d4 100644 --- a/lib/ansible/modules/packaging/os/apt.py +++ b/lib/ansible/modules/packaging/os/apt.py @@ -252,7 +252,6 @@ import sys import time from ansible.module_utils.basic import AnsibleModule -from ansible.module_utils.pycompat24 import get_exception from ansible.module_utils._text import to_bytes, to_native from ansible.module_utils.urls import fetch_url @@ -588,9 +587,8 @@ def install_deb(m, debs, cache, force, install_recommends, allow_unauthenticated # to install so they're all done in one shot deps_to_install.extend(pkg.missing_deps) - except Exception: - e = get_exception() - m.fail_json(msg="Unable to install package: %s" % str(e)) + except Exception as e: + m.fail_json(msg="Unable to install package: %s" % to_native(e)) # and add this deb to the list of packages to install pkgs_to_install.append(deb_file) @@ -805,9 +803,8 @@ def download(module, deb): f.write(data) f.close() deb = package - except Exception: - e = get_exception() - module.fail_json(msg="Failure downloading %s, %s" % (deb, e)) + except Exception as e: + module.fail_json(msg="Failure downloading %s, %s" % (deb, to_native(e))) return deb @@ -843,8 +840,7 @@ def get_cache(module): cache = None try: cache = apt.Cache() - except SystemError: - e = get_exception() + except SystemError as e: if '/var/lib/apt/lists/' in str(e).lower(): # update cache until files are fixed or retries exceeded retries = 0 diff --git a/lib/ansible/modules/packaging/os/apt_repository.py b/lib/ansible/modules/packaging/os/apt_repository.py index 585274b1c5f..e09289f4328 100644 --- a/lib/ansible/modules/packaging/os/apt_repository.py +++ b/lib/ansible/modules/packaging/os/apt_repository.py @@ -107,7 +107,11 @@ import os import re import sys import tempfile - +import json +# import module snippets +from ansible.module_utils.basic import AnsibleModule +from ansible.module_utils.urls import fetch_url +from ansible.module_utils._text import to_native try: import apt import apt_pkg @@ -292,9 +296,8 @@ class SourcesList(object): try: f.write(line) - except IOError: - err = get_exception() - self.module.fail_json(msg="Failed to write to file %s: %s" % (tmp_path, unicode(err))) + except IOError as err: + self.module.fail_json(msg="Failed to write to file %s: %s" % (tmp_path, to_native(err))) self.module.atomic_move(tmp_path, filename) # allow the user to override the default mode @@ -510,9 +513,8 @@ def main(): sourceslist.add_source(repo) elif state == 'absent': sourceslist.remove_source(repo) - except InvalidSource: - err = get_exception() - module.fail_json(msg='Invalid repository string: %s' % unicode(err)) + except InvalidSource as err: + module.fail_json(msg='Invalid repository string: %s' % to_native(err)) sources_after = sourceslist.dump() changed = sources_before != sources_after @@ -533,15 +535,11 @@ def main(): if update_cache: cache = apt.Cache() cache.update() - except OSError: - err = get_exception() - module.fail_json(msg=unicode(err)) + except OSError as err: + module.fail_json(msg=to_native(err)) module.exit_json(changed=changed, repo=repo, state=state, diff=diff) -# import module snippets -from ansible.module_utils.basic import * -from ansible.module_utils.urls import * if __name__ == '__main__': main() diff --git a/lib/ansible/modules/packaging/os/yum_repository.py b/lib/ansible/modules/packaging/os/yum_repository.py index 064a7433ab9..b0235a5b11e 100644 --- a/lib/ansible/modules/packaging/os/yum_repository.py +++ b/lib/ansible/modules/packaging/os/yum_repository.py @@ -448,7 +448,7 @@ state: import os from ansible.module_utils.basic import AnsibleModule -from ansible.module_utils.pycompat24 import get_exception +from ansible.module_utils._text import to_native from ansible.module_utils.six.moves import configparser @@ -566,32 +566,29 @@ class YumRepo(object): # Write data into the file try: fd = open(self.params['dest'], 'w') - except IOError: - e = get_exception() + except IOError as e: self.module.fail_json( msg="Cannot open repo file %s." % self.params['dest'], - details=str(e)) + details=to_native(e)) self.repofile.write(fd) try: fd.close() - except IOError: - e = get_exception() + except IOError as e: self.module.fail_json( msg="Cannot write repo file %s." % self.params['dest'], - details=str(e)) + details=to_native(e)) else: # Remove the file if there are not repos try: os.remove(self.params['dest']) - except OSError: - e = get_exception() + except OSError as e: self.module.fail_json( msg=( "Cannot remove empty repo file %s." % self.params['dest']), - details=str(e)) + details=to_native(e)) def remove(self): # Remove section if exists diff --git a/lib/ansible/modules/storage/netapp/netapp_e_host.py b/lib/ansible/modules/storage/netapp/netapp_e_host.py index 70e8827c2ec..c61b1f6d166 100644 --- a/lib/ansible/modules/storage/netapp/netapp_e_host.py +++ b/lib/ansible/modules/storage/netapp/netapp_e_host.py @@ -66,7 +66,7 @@ import json from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.netapp import request, eseries_host_argument_spec -from ansible.module_utils.pycompat24 import get_exception +from ansible.module_utils._text import to_native HEADERS = { "Content-Type": "application/json", @@ -110,10 +110,9 @@ class Host(object): try: (rc, host_types) = request(self.url + 'storage-systems/%s/host-types' % self.ssid, url_password=self.pwd, url_username=self.user, validate_certs=self.certs, headers=HEADERS) - except Exception: - err = get_exception() + except Exception as err: self.module.fail_json( - msg="Failed to get host types. Array Id [%s]. Error [%s]." % (self.ssid, str(err))) + msg="Failed to get host types. Array Id [%s]. Error [%s]." % (self.ssid, to_native(err))) try: match = filter(lambda host_type: host_type['index'] == self.host_type_index, host_types)[0] @@ -129,10 +128,9 @@ class Host(object): url_password=self.pwd, url_username=self.user, validate_certs=self.certs, headers=HEADERS) - except: - err = get_exception() + except Exception as err: self.module.fail_json( - msg="Failed to get unassociated host ports. Array Id [%s]. Error [%s]." % (self.ssid, str(err))) + msg="Failed to get unassociated host ports. Array Id [%s]. Error [%s]." % (self.ssid, to_native(err))) if len(self.available_ports) > 0 and len(self.ports) <= len(self.available_ports): for port in self.ports: @@ -159,10 +157,9 @@ class Host(object): (rc, all_groups) = request(self.url + 'storage-systems/%s/host-groups' % self.ssid, url_password=self.pwd, url_username=self.user, validate_certs=self.certs, headers=HEADERS) - except: - err = get_exception() + except Exception as err: self.module.fail_json( - msg="Failed to get host groups. Array Id [%s]. Error [%s]." % (self.ssid, str(err))) + msg="Failed to get host groups. Array Id [%s]. Error [%s]." % (self.ssid, to_native(err))) try: group_obj = filter(lambda group: group['name'] == self.group, all_groups)[0] @@ -178,10 +175,9 @@ class Host(object): try: (rc, all_hosts) = request(self.url + 'storage-systems/%s/hosts' % self.ssid, url_password=self.pwd, url_username=self.user, validate_certs=self.certs, headers=HEADERS) - except: - err = get_exception() + except Exception as err: self.module.fail_json( - msg="Failed to determine host existence. Array Id [%s]. Error [%s]." % (self.ssid, str(err))) + msg="Failed to determine host existence. Array Id [%s]. Error [%s]." % (self.ssid, to_native(err))) self.all_hosts = all_hosts try: # Try to grab the host object @@ -260,11 +256,10 @@ class Host(object): self.url + 'storage-systems/%s/hosts/%s' % (self.ssid, self.host_obj['id']), url_username=self.user, url_password=self.pwd, headers=HEADERS, validate_certs=self.certs, method='POST', data=json.dumps(self.post_body)) - except: - err = get_exception() + except Exception as err: self.module.fail_json( msg="Failed to reassign host port. Host Id [%s]. Array Id [%s]. Error [%s]." % ( - self.host_obj['id'], self.ssid, str(err))) + self.host_obj['id'], self.ssid, to_native(err))) def update_host(self): if self.ports: @@ -285,9 +280,8 @@ class Host(object): (rc, self.host_obj) = request(self.url + 'storage-systems/%s/hosts/%s' % (self.ssid, self.host_obj['id']), url_username=self.user, url_password=self.pwd, headers=HEADERS, validate_certs=self.certs, method='POST', data=json.dumps(self.post_body)) - except: - err = get_exception() - self.module.fail_json(msg="Failed to update host. Array Id [%s]. Error [%s]." % (self.ssid, str(err))) + except Exception as err: + self.module.fail_json(msg="Failed to update host. Array Id [%s]. Error [%s]." % (self.ssid, to_native(err))) self.module.exit_json(changed=True, **self.host_obj) @@ -311,10 +305,9 @@ class Host(object): (rc, create_resp) = request(self.url + "storage-systems/%s/hosts" % self.ssid, method='POST', url_username=self.user, url_password=self.pwd, validate_certs=self.certs, data=json.dumps(post_body), headers=HEADERS) - except: - err = get_exception() + except Exception as err: self.module.fail_json( - msg="Failed to create host. Array Id [%s]. Error [%s]." % (self.ssid, str(err))) + msg="Failed to create host. Array Id [%s]. Error [%s]." % (self.ssid, to_native(err))) else: self.module.exit_json(changed=False, msg="Host already exists. Id [%s]. Host [%s]." % (self.ssid, self.name)) @@ -331,12 +324,11 @@ class Host(object): (rc, resp) = request(self.url + "storage-systems/%s/hosts/%s" % (self.ssid, self.host_obj['id']), method='DELETE', url_username=self.user, url_password=self.pwd, validate_certs=self.certs) - except: - err = get_exception() + except Exception as err: self.module.fail_json( msg="Failed to remote host. Host[%s]. Array Id [%s]. Error [%s]." % (self.host_obj['id'], self.ssid, - str(err))) + to_native(err))) def apply(self): if self.state == 'present': diff --git a/lib/ansible/modules/storage/netapp/netapp_e_lun_mapping.py b/lib/ansible/modules/storage/netapp/netapp_e_lun_mapping.py index af050063b12..1d4b0bf1fe2 100644 --- a/lib/ansible/modules/storage/netapp/netapp_e_lun_mapping.py +++ b/lib/ansible/modules/storage/netapp/netapp_e_lun_mapping.py @@ -78,7 +78,7 @@ import json from ansible.module_utils.api import basic_auth_argument_spec from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.netapp import request, eseries_host_argument_spec -from ansible.module_utils.pycompat24 import get_exception +from ansible.module_utils._text import to_native HEADERS = { "Content-Type": "application/json", @@ -94,9 +94,8 @@ def get_host_and_group_map(module, ssid, api_url, user, pwd, validate_certs): try: hg_rc, hg_data = request(groups_url, headers=HEADERS, url_username=user, url_password=pwd, validate_certs=validate_certs) - except: - err = get_exception() - module.fail_json(msg="Failed to get host groups. Id [%s]. Error [%s]" % (ssid, str(err))) + except Exception as err: + module.fail_json(msg="Failed to get host groups. Id [%s]. Error [%s]" % (ssid, to_native(err))) for group in hg_data: mapping['group'][group['name']] = group['id'] @@ -106,9 +105,8 @@ def get_host_and_group_map(module, ssid, api_url, user, pwd, validate_certs): try: h_rc, h_data = request(hosts_url, headers=HEADERS, url_username=user, url_password=pwd, validate_certs=validate_certs) - except: - err = get_exception() - module.fail_json(msg="Failed to get hosts. Id [%s]. Error [%s]" % (ssid, str(err))) + except Exception as err: + module.fail_json(msg="Failed to get hosts. Id [%s]. Error [%s]" % (ssid, to_native(err))) for host in h_data: mapping['host'][host['name']] = host['id'] @@ -150,10 +148,9 @@ def get_volumes(module, ssid, api_url, user, pwd, mappable, validate_certs): url = api_url + volumes try: rc, data = request(url, url_username=user, url_password=pwd, validate_certs=validate_certs) - except Exception: - err = get_exception() + except Exception as err: module.fail_json( - msg="Failed to mappable objects. Type[%s. Id [%s]. Error [%s]." % (mappable, ssid, str(err))) + msg="Failed to mappable objects. Type[%s. Id [%s]. Error [%s]." % (mappable, ssid, to_native(err))) return data diff --git a/lib/ansible/modules/storage/netapp/netapp_e_snapshot_group.py b/lib/ansible/modules/storage/netapp/netapp_e_snapshot_group.py index 300bd430866..7786e195c88 100644 --- a/lib/ansible/modules/storage/netapp/netapp_e_snapshot_group.py +++ b/lib/ansible/modules/storage/netapp/netapp_e_snapshot_group.py @@ -136,7 +136,7 @@ import json from ansible.module_utils.api import basic_auth_argument_spec from ansible.module_utils.basic import AnsibleModule -from ansible.module_utils.pycompat24 import get_exception +from ansible.module_utils._text import to_native from ansible.module_utils.urls import open_url from ansible.module_utils.six.moves.urllib.error import HTTPError @@ -149,8 +149,7 @@ def request(url, data=None, headers=None, method='GET', use_proxy=True, force=force, last_mod_time=last_mod_time, timeout=timeout, validate_certs=validate_certs, url_username=url_username, url_password=url_password, http_agent=http_agent, force_basic_auth=force_basic_auth) - except HTTPError: - err = get_exception() + except HTTPError as err: r = err.fp try: @@ -223,10 +222,9 @@ class SnapshotGroup(object): url = self.url + pools try: (rc, data) = request(url, headers=HEADERS, url_username=self.user, url_password=self.pwd) - except: - err = get_exception() + except Exception as err: self.module.fail_json(msg="Snapshot group module - Failed to fetch storage pools. " + - "Id [%s]. Error [%s]." % (self.ssid, str(err))) + "Id [%s]. Error [%s]." % (self.ssid, to_native(err))) for pool in data: if pool['name'] == self.storage_pool_name: @@ -242,10 +240,9 @@ class SnapshotGroup(object): try: rc, data = request(url, headers=HEADERS, url_username=self.user, url_password=self.pwd, validate_certs=self.certs) - except: - err = get_exception() + except Exception as err: self.module.fail_json(msg="Snapshot group module - Failed to fetch volumes. " + - "Id [%s]. Error [%s]." % (self.ssid, str(err))) + "Id [%s]. Error [%s]." % (self.ssid, to_native(err))) qty = 0 for volume in data: if volume['name'] == self.base_volume_name: @@ -269,10 +266,9 @@ class SnapshotGroup(object): try: rc, data = request(url, headers=HEADERS, url_username=self.user, url_password=self.pwd, validate_certs=self.certs) - except: - err = get_exception() + except Exception as err: self.module.fail_json(msg="Failed to fetch snapshot groups. " + - "Id [%s]. Error [%s]." % (self.ssid, str(err))) + "Id [%s]. Error [%s]." % (self.ssid, to_native(err))) for ssg in data: if ssg['name'] == self.name: self.ssg_data = ssg @@ -305,12 +301,11 @@ class SnapshotGroup(object): try: rc, self.ssg_data = request(url, data=json.dumps(self.post_data), method='POST', headers=HEADERS, url_username=self.user, url_password=self.pwd, validate_certs=self.certs) - except: - err = get_exception() + except Exception as err: self.module.fail_json(msg="Failed to create snapshot group. " + "Snapshot group [%s]. Id [%s]. Error [%s]." % (self.name, self.ssid, - str(err))) + to_native(err))) if not self.snapshot_group_id: self.snapshot_group_id = self.ssg_data['id'] @@ -332,12 +327,11 @@ class SnapshotGroup(object): try: rc, self.ssg_data = request(url, data=json.dumps(self.post_data), method='POST', headers=HEADERS, url_username=self.user, url_password=self.pwd, validate_certs=self.certs) - except: - err = get_exception() + except Exception as err: self.module.fail_json(msg="Failed to update snapshot group. " + "Snapshot group [%s]. Id [%s]. Error [%s]." % (self.name, self.ssid, - str(err))) + to_native(err))) def apply(self): if self.state == 'absent': @@ -347,12 +341,11 @@ class SnapshotGroup(object): self.url + 'storage-systems/%s/snapshot-groups/%s' % (self.ssid, self.snapshot_group_id), method='DELETE', headers=HEADERS, url_password=self.pwd, url_username=self.user, validate_certs=self.certs) - except: - err = get_exception() + except Exception as err: self.module.fail_json(msg="Failed to delete snapshot group. " + "Snapshot group [%s]. Id [%s]. Error [%s]." % (self.name, self.ssid, - str(err))) + to_native(err))) self.module.exit_json(changed=True, msg="Snapshot group removed", **self.ssg_data) else: self.module.exit_json(changed=False, msg="Snapshot group absent") diff --git a/lib/ansible/modules/storage/netapp/netapp_e_snapshot_images.py b/lib/ansible/modules/storage/netapp/netapp_e_snapshot_images.py index 2cd4c20d90c..0320fcbab8d 100644 --- a/lib/ansible/modules/storage/netapp/netapp_e_snapshot_images.py +++ b/lib/ansible/modules/storage/netapp/netapp_e_snapshot_images.py @@ -84,7 +84,7 @@ import json from ansible.module_utils.api import basic_auth_argument_spec from ansible.module_utils.basic import AnsibleModule -from ansible.module_utils.pycompat24 import get_exception +from ansible.module_utils._text import to_native from ansible.module_utils.urls import open_url from ansible.module_utils.six.moves.urllib.error import HTTPError @@ -97,8 +97,7 @@ def request(url, data=None, headers=None, method='GET', use_proxy=True, force=force, last_mod_time=last_mod_time, timeout=timeout, validate_certs=validate_certs, url_username=url_username, url_password=url_password, http_agent=http_agent, force_basic_auth=force_basic_auth) - except HTTPError: - err = get_exception() + except HTTPError as err: r = err.fp try: @@ -145,10 +144,9 @@ def oldest_image(module, ssid, api_url, api_pwd, api_usr, name): try: (ret, images) = request(url, url_username=api_usr, url_password=api_pwd, headers=HEADERS, validate_certs=module.params['validate_certs']) - except: - err = get_exception() + except Exception as err: module.fail_json(msg="Failed to get snapshot images for group. Group [%s]. Id [%s]. Error [%s]" % - (name, ssid, str(err))) + (name, ssid, to_native(err))) if not images: module.exit_json(msg="There are no snapshot images to remove. Group [%s]. Id [%s]." % (name, ssid)) @@ -188,8 +186,7 @@ def delete_image(module, ssid, api_url, pwd, user, snapshot_group): try: (ret, image_data) = request(url, method='DELETE', url_username=user, url_password=pwd, headers=HEADERS, validate_certs=module.params['validate_certs']) - except Exception: - e = get_exception() + except Exception as e: image_data = (e[0], e[1]) if ret == 204: diff --git a/lib/ansible/modules/storage/netapp/netapp_e_snapshot_volume.py b/lib/ansible/modules/storage/netapp/netapp_e_snapshot_volume.py index 064fd306dce..e73b5573eb1 100644 --- a/lib/ansible/modules/storage/netapp/netapp_e_snapshot_volume.py +++ b/lib/ansible/modules/storage/netapp/netapp_e_snapshot_volume.py @@ -111,7 +111,6 @@ import json from ansible.module_utils.api import basic_auth_argument_spec from ansible.module_utils.basic import AnsibleModule -from ansible.module_utils.pycompat24 import get_exception from ansible.module_utils.urls import open_url from ansible.module_utils.six.moves.urllib.error import HTTPError @@ -124,8 +123,7 @@ def request(url, data=None, headers=None, method='GET', use_proxy=True, force=force, last_mod_time=last_mod_time, timeout=timeout, validate_certs=validate_certs, url_username=url_username, url_password=url_password, http_agent=http_agent, force_basic_auth=force_basic_auth) - except HTTPError: - err = get_exception() + except HTTPError as err: r = err.fp try: diff --git a/lib/ansible/modules/storage/netapp/netapp_e_storage_system.py b/lib/ansible/modules/storage/netapp/netapp_e_storage_system.py index 2ce9b97f5cd..d5f90a5a650 100644 --- a/lib/ansible/modules/storage/netapp/netapp_e_storage_system.py +++ b/lib/ansible/modules/storage/netapp/netapp_e_storage_system.py @@ -101,7 +101,7 @@ from time import sleep from ansible.module_utils.api import basic_auth_argument_spec from ansible.module_utils.basic import AnsibleModule -from ansible.module_utils.pycompat24 import get_exception +from ansible.module_utils._text import to_native from ansible.module_utils.urls import open_url from ansible.module_utils.six.moves.urllib.error import HTTPError @@ -114,8 +114,7 @@ def request(url, data=None, headers=None, method='GET', use_proxy=True, force=force, last_mod_time=last_mod_time, timeout=timeout, validate_certs=validate_certs, url_username=url_username, url_password=url_password, http_agent=http_agent, force_basic_auth=force_basic_auth) - except HTTPError: - err = get_exception() + except HTTPError as err: r = err.fp try: @@ -208,9 +207,8 @@ def main(): (rc, resp) = request(api_url + "/storage-systems/%s" % ssid, headers=dict(Accept="application/json"), url_username=api_usr, url_password=api_pwd, validate_certs=validate_certs, ignore_errors=True) - except: - err = get_exception() - module.fail_json(msg="Error accessing storage-system with id [%s]. Error [%s]" % (ssid, str(err))) + except Exception as err: + module.fail_json(msg="Error accessing storage-system with id [%s]. Error [%s]" % (ssid, to_native(err))) array_exists = True array_detail = resp @@ -260,10 +258,9 @@ def main(): try: (rc, resp) = do_post(ssid, api_url, post_headers, api_usr, api_pwd, validate_certs, request_data, array_status_timeout_sec) - except: - err = get_exception() + except Exception as err: module.fail_json(msg="Failed to add storage system. Id[%s]. Request body [%s]. Error[%s]." % - (ssid, request_data, str(err))) + (ssid, request_data, to_native(err))) else: # array exists, modify... post_headers = dict(Accept="application/json") @@ -278,10 +275,9 @@ def main(): try: (rc, resp) = do_post(ssid, api_url, post_headers, api_usr, api_pwd, validate_certs, post_body, array_status_timeout_sec) - except: - err = get_exception() + except Exception as err: module.fail_json(msg="Failed to update storage system. Id[%s]. Request body [%s]. Error[%s]." % - (ssid, post_body, str(err))) + (ssid, post_body, to_native(err))) elif state == 'absent': # delete the array @@ -289,9 +285,8 @@ def main(): (rc, resp) = request(api_url + "/storage-systems/%s" % ssid, method='DELETE', url_username=api_usr, url_password=api_pwd, validate_certs=validate_certs) - except: - err = get_exception() - module.fail_json(msg="Failed to remove storage array. Id[%s]. Error[%s]." % (ssid, str(err))) + except Exception as err: + module.fail_json(msg="Failed to remove storage array. Id[%s]. Error[%s]." % (ssid, to_native(err))) if rc == 422: module.exit_json(changed=changed, msg="Storage system was not presnt.") diff --git a/lib/ansible/modules/storage/netapp/netapp_e_storagepool.py b/lib/ansible/modules/storage/netapp/netapp_e_storagepool.py index e0a0c7dc948..40076b5598b 100644 --- a/lib/ansible/modules/storage/netapp/netapp_e_storagepool.py +++ b/lib/ansible/modules/storage/netapp/netapp_e_storagepool.py @@ -109,7 +109,7 @@ from traceback import format_exc from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.netapp import request, eseries_host_argument_spec -from ansible.module_utils.pycompat24 import get_exception +from ansible.module_utils._text import to_native def select(predicate, iterable): @@ -380,17 +380,15 @@ class NetAppESeriesStoragePool(object): (rc, resp) = request(self.api_url + "/storage-systems/%s/storage-pools" % (self.ssid), headers=dict(Accept="application/json"), url_username=self.api_usr, url_password=self.api_pwd, validate_certs=self.validate_certs) - except Exception: - err = get_exception() + except Exception as err: rc = err.args[0] if rc == 404 and self.state == 'absent': self.module.exit_json( msg="Storage pool [%s] did not exist." % (self.name)) else: - err = get_exception() self.module.exit_json( msg="Failed to get storage pools. Array id [%s]. Error[%s]. State[%s]. RC[%s]." % - (self.ssid, str(err), self.state, rc)) + (self.ssid, to_native(err), self.state, rc)) self.debug("searching for storage pool '%s'", storage_pool_name) @@ -435,10 +433,9 @@ class NetAppESeriesStoragePool(object): (rc, drives_resp) = request(self.api_url + "/storage-systems/%s/drives" % (self.ssid), method='GET', url_username=self.api_usr, url_password=self.api_pwd, validate_certs=self.validate_certs) - except: - err = get_exception() + except Exception as err: self.module.exit_json( - msg="Failed to fetch disk drives. Array id [%s]. Error[%s]." % (self.ssid, str(err))) + msg="Failed to fetch disk drives. Array id [%s]. Error[%s]." % (self.ssid, to_native(err))) try: candidate_set = self.filter_drives(drives_resp, @@ -451,10 +448,9 @@ class NetAppESeriesStoragePool(object): interface_type=self.criteria_drive_interface_type, fde_required=self.criteria_drive_require_fde ) - except: - err = get_exception() + except Exception as err: self.module.fail_json( - msg="Failed to allocate adequate drive count. Id [%s]. Error [%s]." % (self.ssid, str(err))) + msg="Failed to allocate adequate drive count. Id [%s]. Error [%s]." % (self.ssid, to_native(err))) disk_ids = [d['id'] for d in candidate_set] @@ -478,13 +474,12 @@ class NetAppESeriesStoragePool(object): url_username=self.api_usr, url_password=self.api_pwd, validate_certs=self.validate_certs, timeout=120) - except: - err = get_exception() + except Exception as err: pool_id = self.pool_detail['id'] self.module.exit_json( msg="Failed to create storage pool. Pool id [%s]. Array id [%s]. Error[%s]." % (pool_id, self.ssid, - str(err))) + to_native(err))) self.pool_detail = self.get_storage_pool(self.name) @@ -496,13 +491,12 @@ class NetAppESeriesStoragePool(object): data=json.dumps(secure_pool_data), headers=self.post_headers, method='POST', url_username=self.api_usr, url_password=self.api_pwd, validate_certs=self.validate_certs, timeout=120, ignore_errors=True) - except: - err = get_exception() + except Exception as err: pool_id = self.pool_detail['id'] self.module.exit_json( msg="Failed to update storage pool. Pool id [%s]. Array id [%s]. Error[%s]." % (pool_id, self.ssid, - str(err))) + to_native(err))) @property def needs_raid_level_migration(self): @@ -527,12 +521,11 @@ class NetAppESeriesStoragePool(object): data=json.dumps(sp_raid_migrate_req), headers=self.post_headers, method='POST', url_username=self.api_usr, url_password=self.api_pwd, validate_certs=self.validate_certs, timeout=120) - except: - err = get_exception() + except Exception as err: pool_id = self.pool_detail['id'] self.module.exit_json( msg="Failed to change the raid level of storage pool. Pool id [%s]. Array id [%s]. Error[%s]." % ( - pool_id, self.ssid, str(err))) + pool_id, self.ssid, to_native(err))) @property def sp_drives(self, exclude_hotspares=True): @@ -543,11 +536,10 @@ class NetAppESeriesStoragePool(object): (rc, resp) = request(self.api_url + "/storage-systems/%s/drives" % (self.ssid), method='GET', url_username=self.api_usr, url_password=self.api_pwd, validate_certs=self.validate_certs) - except: - err = get_exception() + except Exception as err: pool_id = self.pool_detail['id'] self.module.exit_json( - msg="Failed to fetch disk drives. Pool id [%s]. Array id [%s]. Error[%s]." % (pool_id, self.ssid, str(err))) + msg="Failed to fetch disk drives. Pool id [%s]. Array id [%s]. Error[%s]." % (pool_id, self.ssid, to_native(err))) sp_id = self.pool_detail['id'] if exclude_hotspares: @@ -586,12 +578,11 @@ class NetAppESeriesStoragePool(object): self.pool_detail['id']), method='GET', url_username=self.api_usr, url_password=self.api_pwd, validate_certs=self.validate_certs, timeout=120) - except: - err = get_exception() + except Exception as err: pool_id = self.pool_detail['id'] self.module.exit_json( msg="Failed to fetch candidate drives for storage pool. Pool id [%s]. Array id [%s]. Error[%s]." % ( - pool_id, self.ssid, str(err))) + pool_id, self.ssid, to_native(err))) current_drive_count = len(self.sp_drives) current_capacity_bytes = int(self.pool_detail['totalRaidedSpace']) # TODO: is this the right attribute to use? @@ -649,14 +640,12 @@ class NetAppESeriesStoragePool(object): self.pool_detail['id']), data=json.dumps(sp_expand_req), headers=self.post_headers, method='POST', url_username=self.api_usr, url_password=self.api_pwd, validate_certs=self.validate_certs, timeout=120) - except: - err = get_exception() + except Exception as err: pool_id = self.pool_detail['id'] self.module.exit_json( msg="Failed to add drives to storage pool. Pool id [%s]. Array id [%s]. Error[%s]." % (pool_id, self.ssid, - str( - err))) + to_native(err))) # TODO: check response # TODO: support blocking wait? @@ -675,12 +664,11 @@ class NetAppESeriesStoragePool(object): self.pool_detail['id']), data=json.dumps(drive_list), headers=self.post_headers, method='POST', url_username=self.api_usr, url_password=self.api_pwd, validate_certs=self.validate_certs, timeout=120) - except: - err = get_exception() + except Exception as err: pool_id = self.pool_detail['id'] self.module.exit_json( msg="Failed to remove drives from storage pool. Pool id [%s]. Array id [%s]. Error[%s]." % ( - pool_id, self.ssid, str(err))) + pool_id, self.ssid, to_native(err))) def update_reserve_drive_count(self, qty): data = dict(reservedDriveCount=qty) @@ -689,14 +677,12 @@ class NetAppESeriesStoragePool(object): self.api_url + "/storage-systems/%s/storage-pools/%s" % (self.ssid, self.pool_detail['id']), data=json.dumps(data), headers=self.post_headers, method='POST', url_username=self.api_usr, url_password=self.api_pwd, validate_certs=self.validate_certs, timeout=120) - except: - err = get_exception() + except Exception as err: pool_id = self.pool_detail['id'] self.module.exit_json( msg="Failed to update reserve drive count. Pool id [%s]. Array id [%s]. Error[%s]." % (pool_id, self.ssid, - str( - err))) + to_native(err))) def apply(self): changed = False @@ -777,11 +763,10 @@ class NetAppESeriesStoragePool(object): data=json.dumps(secure_pool_data), headers=self.post_headers, method='POST', url_username=self.api_usr, url_password=self.api_pwd, validate_certs=self.validate_certs, timeout=120, ignore_errors=True) - except: - err = get_exception() + except Exception as err: self.module.exit_json( msg="Failed to delete storage pool. Pool id [%s]. Array id [%s]. Error[%s]." % ( - pool_id, self.ssid, str(err))) + pool_id, self.ssid, to_native(err))) if int(retc) == 422: self.module.fail_json( @@ -799,12 +784,11 @@ class NetAppESeriesStoragePool(object): method='DELETE', url_username=self.api_usr, url_password=self.api_pwd, validate_certs=self.validate_certs, timeout=120) - except: - err = get_exception() + except Exception as err: self.module.exit_json( msg="Failed to delete storage pool. Pool id [%s]. Array id [%s]. Error[%s]." % (pool_id, self.ssid, - str(err))) + to_native(err))) self.module.exit_json(changed=changed, **self.pool_detail) @@ -813,9 +797,8 @@ def main(): sp = NetAppESeriesStoragePool() try: sp.apply() - except Exception: - e = get_exception() - sp.debug("Exception in apply(): \n%s", format_exc(e)) + except Exception as e: + sp.debug("Exception in apply(): \n%s", format_exc()) raise diff --git a/lib/ansible/modules/storage/netapp/netapp_e_volume.py b/lib/ansible/modules/storage/netapp/netapp_e_volume.py index 45620581844..d20c5803b1d 100644 --- a/lib/ansible/modules/storage/netapp/netapp_e_volume.py +++ b/lib/ansible/modules/storage/netapp/netapp_e_volume.py @@ -117,7 +117,7 @@ from traceback import format_exc from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.netapp import request, eseries_host_argument_spec -from ansible.module_utils.pycompat24 import get_exception +from ansible.module_utils._text import to_native HEADERS = { "Content-Type": "application/json", @@ -217,21 +217,19 @@ class NetAppESeriesVolume(object): (rc, volumes) = request(self.api_url + "/storage-systems/%s/volumes" % (self.ssid), headers=dict(Accept="application/json"), url_username=self.api_usr, url_password=self.api_pwd, validate_certs=self.validate_certs) - except Exception: - err = get_exception() + except Exception as err: self.module.fail_json( msg="Failed to obtain list of standard/thick volumes. Array Id [%s]. Error[%s]." % (self.ssid, - str(err))) + to_native(err))) try: self.debug('fetching thin-volumes') (rc, thinvols) = request(self.api_url + "/storage-systems/%s/thin-volumes" % (self.ssid), headers=dict(Accept="application/json"), url_username=self.api_usr, url_password=self.api_pwd, validate_certs=self.validate_certs) - except Exception: - err = get_exception() + except Exception as err: self.module.fail_json( - msg="Failed to obtain list of thin volumes. Array Id [%s]. Error[%s]." % (self.ssid, str(err))) + msg="Failed to obtain list of thin volumes. Array Id [%s]. Error[%s]." % (self.ssid, to_native(err))) volumes.extend(thinvols) @@ -252,10 +250,9 @@ class NetAppESeriesVolume(object): (rc, resp) = request(self.api_url + "/storage-systems/%s/storage-pools" % (self.ssid), headers=dict(Accept="application/json"), url_username=self.api_usr, url_password=self.api_pwd, validate_certs=self.validate_certs) - except Exception: - err = get_exception() + except Exception as err: self.module.fail_json( - msg="Failed to obtain list of storage pools. Array Id [%s]. Error[%s]." % (self.ssid, str(err))) + msg="Failed to obtain list of storage pools. Array Id [%s]. Error[%s]." % (self.ssid, to_native(err))) self.debug("searching for storage pool '%s'", storage_pool_name) pool_detail = next(ifilter(lambda a: a['name'] == storage_pool_name, resp), None) @@ -284,11 +281,10 @@ class NetAppESeriesVolume(object): url_username=self.api_usr, url_password=self.api_pwd, validate_certs=self.validate_certs, timeout=120) - except Exception: - err = get_exception() + except Exception as err: self.module.fail_json( msg="Failed to create volume. Volume [%s]. Array Id [%s]. Error[%s]." % (self.name, self.ssid, - str(err))) + to_native(err))) def create_thin_volume(self, pool_id, name, size_unit, size, thin_volume_repo_size, thin_volume_max_repo_size, data_assurance_enabled): @@ -309,12 +305,11 @@ class NetAppESeriesVolume(object): url_username=self.api_usr, url_password=self.api_pwd, validate_certs=self.validate_certs, timeout=120) - except Exception: - err = get_exception() + except Exception as err: self.module.fail_json( msg="Failed to create thin volume. Volume [%s]. Array Id [%s]. Error[%s]." % (self.name, self.ssid, - str(err))) + to_native(err))) def delete_volume(self): # delete the volume @@ -325,11 +320,10 @@ class NetAppESeriesVolume(object): self.volume_detail['id']), method='DELETE', url_username=self.api_usr, url_password=self.api_pwd, validate_certs=self.validate_certs, timeout=120) - except Exception: - err = get_exception() + except Exception as err: self.module.fail_json( msg="Failed to delete volume. Volume [%s]. Array Id [%s]. Error[%s]." % (self.name, self.ssid, - str(err))) + to_native(err))) @property def volume_resource_name(self): @@ -366,12 +360,11 @@ class NetAppESeriesVolume(object): data=json.dumps(update_volume_req), headers=HEADERS, method='POST', url_username=self.api_usr, url_password=self.api_pwd, validate_certs=self.validate_certs, timeout=120) - except Exception: - err = get_exception() + except Exception as err: self.module.fail_json( msg="Failed to update volume properties. Volume [%s]. Array Id [%s]. Error[%s]." % (self.name, self.ssid, - str(err))) + to_native(err))) @property def volume_needs_expansion(self): @@ -399,12 +392,11 @@ class NetAppESeriesVolume(object): data=json.dumps(thin_volume_expand_req), headers=HEADERS, method='POST', url_username=self.api_usr, url_password=self.api_pwd, validate_certs=self.validate_certs, timeout=120) - except Exception: - err = get_exception() + except Exception as err: self.module.fail_json( msg="Failed to expand thin volume. Volume [%s]. Array Id [%s]. Error[%s]." % (self.name, self.ssid, - str(err))) + to_native(err))) # TODO: check return code else: @@ -420,12 +412,11 @@ class NetAppESeriesVolume(object): data=json.dumps(volume_expand_req), headers=HEADERS, method='POST', url_username=self.api_usr, url_password=self.api_pwd, validate_certs=self.validate_certs, timeout=120) - except Exception: - err = get_exception() + except Exception as err: self.module.fail_json( msg="Failed to expand volume. Volume [%s]. Array Id [%s]. Error[%s]." % (self.name, self.ssid, - str(err))) + to_native(err))) self.debug('polling for completion...') @@ -436,11 +427,10 @@ class NetAppESeriesVolume(object): 'id']), method='GET', url_username=self.api_usr, url_password=self.api_pwd, validate_certs=self.validate_certs) - except Exception: - err = get_exception() + except Exception as err: self.module.fail_json( msg="Failed to get volume expansion progress. Volume [%s]. Array Id [%s]. Error[%s]." % ( - self.name, self.ssid, str(err))) + self.name, self.ssid, to_native(err))) action = resp['action'] percent_complete = resp['percentComplete'] @@ -538,10 +528,9 @@ def main(): try: v.apply() - except Exception: - e = get_exception() - v.debug("Exception in apply(): \n%s", format_exc(e)) - v.module.fail_json(msg="Module failed. Error [%s]." % (str(e))) + except Exception as e: + v.debug("Exception in apply(): \n%s", format_exc()) + v.module.fail_json(msg="Module failed. Error [%s]." % to_native(e)) if __name__ == '__main__': diff --git a/lib/ansible/modules/storage/netapp/netapp_e_volume_copy.py b/lib/ansible/modules/storage/netapp/netapp_e_volume_copy.py index cb2f8fe59f5..c6c85cc13b1 100644 --- a/lib/ansible/modules/storage/netapp/netapp_e_volume_copy.py +++ b/lib/ansible/modules/storage/netapp/netapp_e_volume_copy.py @@ -98,7 +98,7 @@ msg: import json from ansible.module_utils.basic import AnsibleModule -from ansible.module_utils.pycompat24 import get_exception +from ansible.module_utils._text import to_native from ansible.module_utils.netapp import request HEADERS = { @@ -284,9 +284,8 @@ def main(): if params['search_volume_id'] is not None: try: potential_targets, potential_sources = find_valid_copy_pair_targets_and_sources(params) - except: - e = get_exception() - module.fail_json(msg="Failed to find valid copy pair candidates. Error [%s]" % str(e)) + except Exception as e: + module.fail_json(msg="Failed to find valid copy pair candidates. Error [%s]" % to_native(e)) module.exit_json(changed=False, msg=' Valid source devices found: %s Valid target devices found: %s' % (len(potential_sources), len(potential_targets)), diff --git a/lib/ansible/modules/storage/netapp/sf_volume_manager.py b/lib/ansible/modules/storage/netapp/sf_volume_manager.py index 15455a55fbf..aeb4dfe7e78 100644 --- a/lib/ansible/modules/storage/netapp/sf_volume_manager.py +++ b/lib/ansible/modules/storage/netapp/sf_volume_manager.py @@ -138,7 +138,7 @@ msg: """ from ansible.module_utils.basic import AnsibleModule -from ansible.module_utils.pycompat24 import get_exception +from ansible.module_utils._text import to_native import ansible.module_utils.netapp as netapp_utils HAS_SF_SDK = netapp_utils.has_sf_sdk() @@ -230,19 +230,17 @@ class SolidFireVolume(object): qos=self.qos, attributes=self.attributes) - except: - err = get_exception() + except Exception as err: self.module.fail_json(msg="Error provisioning volume %s of size %s" % (self.name, self.size), - exception=str(err)) + exception=to_native(err)) def delete_volume(self): try: self.sfe.delete_volume(volume_id=self.volume_id) - except: - err = get_exception() + except Exception as err: self.module.fail_json(msg="Error deleting volume %s" % self.volume_id, - exception=str(err)) + exception=to_native(err)) def update_volume(self): try: @@ -253,10 +251,9 @@ class SolidFireVolume(object): total_size=self.size, attributes=self.attributes) - except: - err = get_exception() + except Exception as err: self.module.fail_json(msg="Error updating volume %s" % self.name, - exception=str(err)) + exception=to_native(err)) def apply(self): changed = False @@ -326,5 +323,6 @@ def main(): v = SolidFireVolume() v.apply() + if __name__ == '__main__': main() diff --git a/lib/ansible/modules/system/known_hosts.py b/lib/ansible/modules/system/known_hosts.py index 39579eb7e56..91d9994a470 100644 --- a/lib/ansible/modules/system/known_hosts.py +++ b/lib/ansible/modules/system/known_hosts.py @@ -81,7 +81,7 @@ import tempfile import errno import re -from ansible.module_utils.pycompat24 import get_exception +from ansible.module_utils._text import to_native from ansible.module_utils.basic import AnsibleModule @@ -132,8 +132,7 @@ def enforce_state(module, params): if replace_or_add or found != (state == "present"): try: inf = open(path, "r") - except IOError: - e = get_exception() + except IOError as e: if e.errno == errno.ENOENT: inf = None else: @@ -150,9 +149,8 @@ def enforce_state(module, params): outf.write(key) outf.flush() module.atomic_move(outf.name, path) - except (IOError, OSError): - e = get_exception() - module.fail_json(msg="Failed to write to file %s: %s" % (path, str(e))) + except (IOError, OSError) as e: + module.fail_json(msg="Failed to write to file %s: %s" % (path, to_native(e))) try: outf.close() @@ -185,10 +183,9 @@ def sanity_check(module, host, key, sshkeygen): outf = tempfile.NamedTemporaryFile(mode='w+') outf.write(key) outf.flush() - except IOError: - e = get_exception() + except IOError as e: module.fail_json(msg="Failed to write to temporary file %s: %s" % - (outf.name, str(e))) + (outf.name, to_native(e))) sshkeygen_command = [sshkeygen, '-F', host, '-f', outf.name] rc, stdout, stderr = module.run_command(sshkeygen_command, check_rc=True) @@ -299,8 +296,7 @@ def compute_diff(path, found_line, replace_or_add, state, key): } try: inf = open(path, "r") - except IOError: - e = get_exception() + except IOError as e: if e.errno == errno.ENOENT: diff['before_header'] = '/dev/null' else: @@ -331,5 +327,6 @@ def main(): results = enforce_state(module, module.params) module.exit_json(**results) + if __name__ == '__main__': main() diff --git a/lib/ansible/modules/system/locale_gen.py b/lib/ansible/modules/system/locale_gen.py index 649de5e02f4..fd2035a7389 100644 --- a/lib/ansible/modules/system/locale_gen.py +++ b/lib/ansible/modules/system/locale_gen.py @@ -43,7 +43,6 @@ import re from subprocess import Popen, PIPE, call from ansible.module_utils.basic import AnsibleModule -from ansible.module_utils.pycompat24 import get_exception from ansible.module_utils._text import to_native LOCALE_NORMALIZATION = { @@ -228,9 +227,8 @@ def main(): apply_change(state, name) else: apply_change_ubuntu(state, name) - except EnvironmentError: - e = get_exception() - module.fail_json(msg=e.strerror, exitValue=e.errno) + except EnvironmentError as e: + module.fail_json(msg=to_native(e), exitValue=e.errno) module.exit_json(name=name, changed=changed, msg="OK") diff --git a/lib/ansible/modules/system/mount.py b/lib/ansible/modules/system/mount.py index f6683629966..2d36b6ac063 100644 --- a/lib/ansible/modules/system/mount.py +++ b/lib/ansible/modules/system/mount.py @@ -128,7 +128,6 @@ import os from ansible.module_utils.basic import AnsibleModule, get_platform from ansible.module_utils.ismount import ismount -from ansible.module_utils.pycompat24 import get_exception from ansible.module_utils.six import iteritems from ansible.module_utils._text import to_native @@ -653,9 +652,8 @@ def main(): if os.path.exists(name): try: os.rmdir(name) - except (OSError, IOError): - e = get_exception() - module.fail_json(msg="Error rmdir %s: %s" % (name, str(e))) + except (OSError, IOError) as e: + module.fail_json(msg="Error rmdir %s: %s" % (name, to_native(e))) elif state == 'unmounted': if ismount(name) or is_bind_mounted(module, linux_mounts, name): if not module.check_mode: @@ -670,10 +668,9 @@ def main(): if not os.path.exists(name) and not module.check_mode: try: os.makedirs(name) - except (OSError, IOError): - e = get_exception() + except (OSError, IOError) as e: module.fail_json( - msg="Error making dir %s: %s" % (name, str(e))) + msg="Error making dir %s: %s" % (name, to_native(e))) name, changed = set_mount(module, args) res = 0 diff --git a/lib/ansible/modules/system/pamd.py b/lib/ansible/modules/system/pamd.py index 652736fe7a4..9289ec3f603 100644 --- a/lib/ansible/modules/system/pamd.py +++ b/lib/ansible/modules/system/pamd.py @@ -255,7 +255,7 @@ dest: from ansible.module_utils.basic import AnsibleModule -from ansible.module_utils.pycompat24 import get_exception +from ansible.module_utils._text import to_native import os import re import time @@ -360,11 +360,10 @@ class PamdService(object): stringline += '\n' self.load_rules_from_string(stringline.replace("\\\n", "")) - except IOError: - e = get_exception() + except IOError as e: self.ansible.fail_json(msg='Unable to open/read PAM module \ file %s with error %s. And line %s' % - (self.fname, str(e), stringline)) + (self.fname, to_native(e), stringline)) def load_rules_from_string(self, stringvalue): for line in stringvalue.splitlines(): @@ -687,5 +686,6 @@ def main(): module.exit_json(changed=change, ansible_facts=facts) + if __name__ == '__main__': main() diff --git a/lib/ansible/modules/system/user.py b/lib/ansible/modules/system/user.py index 06685a55169..bc1c15423b3 100644 --- a/lib/ansible/modules/system/user.py +++ b/lib/ansible/modules/system/user.py @@ -229,7 +229,6 @@ import time from ansible.module_utils._text import to_native from ansible.module_utils.basic import load_platform_subclass, AnsibleModule -from ansible.module_utils.pycompat24 import get_exception try: import spwd @@ -298,9 +297,8 @@ class User(object): if module.params['expires']: try: self.expires = time.gmtime(module.params['expires']) - except Exception: - e = get_exception() - module.fail_json(msg="Invalid expires time %s: %s" % (self.expires, e)) + except Exception as e: + module.fail_json(msg="Invalid expires time %s: %s" % (self.expires, to_native(e))) if module.params['ssh_key_file'] is not None: self.ssh_file = module.params['ssh_key_file'] @@ -637,9 +635,8 @@ class User(object): try: os.mkdir(ssh_dir, int('0700', 8)) os.chown(ssh_dir, info[2], info[3]) - except OSError: - e = get_exception() - return (1, '', 'Failed to create %s: %s' % (ssh_dir, str(e))) + except OSError as e: + return (1, '', 'Failed to create %s: %s' % (ssh_dir, to_native(e))) if os.path.exists(ssh_key_file): return (None, 'Key already exists', '') cmd = [self.module.get_bin_path('ssh-keygen', True)] @@ -709,15 +706,13 @@ class User(object): if os.path.exists(skeleton): try: shutil.copytree(skeleton, path, symlinks=True) - except OSError: - e = get_exception() - self.module.exit_json(failed=True, msg="%s" % e) + except OSError as e: + self.module.exit_json(failed=True, msg="%s" % to_native(e)) else: try: os.makedirs(path) - except OSError: - e = get_exception() - self.module.exit_json(failed=True, msg="%s" % e) + except OSError as e: + self.module.exit_json(failed=True, msg="%s" % to_native(e)) def chown_homedir(self, uid, gid, path): try: @@ -727,9 +722,8 @@ class User(object): os.chown(os.path.join(root, d), uid, gid) for f in files: os.chown(os.path.join(root, f), uid, gid) - except OSError: - e = get_exception() - self.module.exit_json(failed=True, msg="%s" % e) + except OSError as e: + self.module.exit_json(failed=True, msg="%s" % to_native(e)) # =========================================== @@ -1289,9 +1283,8 @@ class SunOS(User): maxweeks = value.rstrip('\n') elif key == "WARNWEEKS": warnweeks = value.rstrip('\n') - except Exception: - err = get_exception() - self.module.fail_json(msg="failed to read /etc/default/passwd: %s" % str(err)) + except Exception as err: + self.module.fail_json(msg="failed to read /etc/default/passwd: %s" % to_native(err)) return (minweeks, maxweeks, warnweeks) @@ -1372,9 +1365,8 @@ class SunOS(User): line = ':'.join(fields) lines.append('%s\n' % line) open(self.SHADOWFILE, 'w+').writelines(lines) - except Exception: - err = get_exception() - self.module.fail_json(msg="failed to update users password: %s" % str(err)) + except Exception as err: + self.module.fail_json(msg="failed to update users password: %s" % to_native(err)) return (rc, out, err) @@ -1468,9 +1460,8 @@ class SunOS(User): lines.append('%s\n' % line) open(self.SHADOWFILE, 'w+').writelines(lines) rc = 0 - except Exception: - err = get_exception() - self.module.fail_json(msg="failed to update users password: %s" % str(err)) + except Exception as err: + self.module.fail_json(msg="failed to update users password: %s" % to_native(err)) return (rc, out, err) diff --git a/lib/ansible/modules/web_infrastructure/htpasswd.py b/lib/ansible/modules/web_infrastructure/htpasswd.py index 1ce0fc1f44a..350a400fb3d 100644 --- a/lib/ansible/modules/web_infrastructure/htpasswd.py +++ b/lib/ansible/modules/web_infrastructure/htpasswd.py @@ -96,7 +96,8 @@ EXAMPLES = """ import os import tempfile from distutils.version import LooseVersion - +from ansible.module_utils.basic import AnsibleModule +from ansible.module_utils._text import to_native try: from passlib.apache import HtpasswdFile, htpasswd_context from passlib.context import CryptContext @@ -262,14 +263,9 @@ def main(): check_file_attrs(module, changed, msg) module.exit_json(msg=msg, changed=changed) - except Exception: - e = get_exception() - module.fail_json(msg=str(e)) + except Exception as e: + module.fail_json(msg=to_native(e)) -# import module snippets -from ansible.module_utils.basic import AnsibleModule -from ansible.module_utils.pycompat24 import get_exception - if __name__ == '__main__': main() diff --git a/lib/ansible/modules/web_infrastructure/jenkins_plugin.py b/lib/ansible/modules/web_infrastructure/jenkins_plugin.py index aaad1189fee..869331b43ef 100644 --- a/lib/ansible/modules/web_infrastructure/jenkins_plugin.py +++ b/lib/ansible/modules/web_infrastructure/jenkins_plugin.py @@ -276,7 +276,6 @@ state: ''' from ansible.module_utils.basic import AnsibleModule -from ansible.module_utils.pycompat24 import get_exception from ansible.module_utils.six.moves.urllib.parse import urlencode from ansible.module_utils.urls import fetch_url, url_argument_spec from ansible.module_utils._text import to_native @@ -325,8 +324,7 @@ class JenkinsPlugin(object): # Parse the JSON data try: json_data = json.loads(to_native(r.read())) - except Exception: - e = get_exception() + except Exception as e: self.module.fail_json( msg="Cannot parse %s JSON data." % what, details=to_native(e)) @@ -350,8 +348,7 @@ class JenkinsPlugin(object): if info['status'] != 200: self.module.fail_json(msg=msg_status, details=info['msg']) - except Exception: - e = get_exception() + except Exception as e: self.module.fail_json(msg=msg_exception, details=to_native(e)) return response @@ -500,11 +497,10 @@ class JenkinsPlugin(object): try: sha1_old = hashlib.sha1(open(plugin_file, 'rb').read()) - except Exception: - e = get_exception() + except Exception as e: self.module.fail_json( msg="Cannot calculate SHA1 of the old plugin.", - details=e.message) + details=to_native(e)) sha1sum_old = base64.b64encode(sha1_old.digest()) @@ -567,8 +563,7 @@ class JenkinsPlugin(object): try: os.close(update_fd) - except IOError: - e = get_exception() + except IOError as e: self.module.fail_json( msg="Cannot close the tmp updates file %s." % updates_file, details=to_native(e)) @@ -576,8 +571,7 @@ class JenkinsPlugin(object): # Open the updates file try: f = open(updates_file) - except IOError: - e = get_exception() + except IOError as e: self.module.fail_json( msg="Cannot open temporal updates file.", details=to_native(e)) @@ -588,11 +582,10 @@ class JenkinsPlugin(object): if i == 1: try: data = json.loads(line) - except Exception: - e = get_exception() + except Exception as e: self.module.fail_json( msg="Cannot load JSON data from the tmp updates file.", - details=e.message) + details=to_native(e)) break @@ -604,11 +597,10 @@ class JenkinsPlugin(object): if not os.path.isdir(updates_dir): try: os.makedirs(updates_dir, int('0700', 8)) - except OSError: - e = get_exception() + except OSError as e: self.module.fail_json( msg="Cannot create temporal directory.", - details=e.message) + details=to_native(e)) self.module.atomic_move(updates_file, updates_file_orig) @@ -639,8 +631,7 @@ class JenkinsPlugin(object): try: os.close(tmp_f_fd) - except IOError: - e = get_exception() + except IOError as e: self.module.fail_json( msg='Cannot close the temporal plugin file %s.' % tmp_f, details=to_native(e)) @@ -766,8 +757,7 @@ def main(): # Convert timeout to float try: module.params['timeout'] = float(module.params['timeout']) - except ValueError: - e = get_exception() + except ValueError as e: module.fail_json( msg='Cannot convert %s to float.' % module.params['timeout'], details=to_native(e)) diff --git a/lib/ansible/modules/web_infrastructure/taiga_issue.py b/lib/ansible/modules/web_infrastructure/taiga_issue.py index 3253d51cf78..18c787ce73a 100644 --- a/lib/ansible/modules/web_infrastructure/taiga_issue.py +++ b/lib/ansible/modules/web_infrastructure/taiga_issue.py @@ -117,7 +117,8 @@ EXAMPLES = ''' RETURN = '''# ''' from os import getenv from os.path import isfile - +from ansible.module_utils.basic import AnsibleModule +from ansible.module_utils._text import to_native try: from taiga import TaigaAPI from taiga.exceptions import TaigaException @@ -235,9 +236,8 @@ def manage_issue(module, taiga_host, project_name, issue_subject, issue_priority # More than 1 matching issue return (False, changed, "More than one issue with subject %s in project %s" % (issue_subject, project_name), {}) - except TaigaException: - exc = get_exception() - msg = "An exception happened: %s" % exc + except TaigaException as exc: + msg = "An exception happened: %s" % to_native(exc) return (False, changed, msg, {}) @@ -307,8 +307,5 @@ def main(): module.fail_json(msg=msg) -from ansible.module_utils.basic import AnsibleModule -from ansible.module_utils.pycompat24 import get_exception - if __name__ == '__main__': main()