2.6 KiB
2.6 KiB
import
Ansible allows unchecked imports of some libraries from specific
directories, listed at the bottom of this section. Import all other
Python libraries in a try/except ImportError block to support sanity
tests such as validate-modules
and to allow Ansible to give
better error messages to the user. To import a library in a try/except
ImportError block:
In modules:
# Instead of 'import another_library', do: import traceback try: import another_library except ImportError: = False HAS_ANOTHER_LIBRARY = traceback.format_exc() ANOTHER_LIBRARY_IMPORT_ERROR else: = True HAS_ANOTHER_LIBRARY # Later in module code: = AnsibleModule(...) module if not HAS_ANOTHER_LIBRARY: # Needs: from ansible.module_utils.basic import missing_required_lib module.fail_json(=missing_required_lib('another_library'), msg=ANOTHER_LIBRARY_IMPORT_ERROR) exception
In plugins:
# Instead of 'import another_library', do: from ansible.module_utils.six import raise_from try: import another_library except ImportError as imp_exc: = imp_exc ANOTHER_LIBRARY_IMPORT_ERROR else: = None ANOTHER_LIBRARY_IMPORT_ERROR # Later in plugin code, for example in __init__ of the plugin: if ANOTHER_LIBRARY_IMPORT_ERROR: raise_from('another_library must be installed to use this plugin'), AnsibleError( ANOTHER_LIBRARY_IMPORT_ERROR)# If you target only newer Python 3 versions, you can also use the # 'raise ... from ...' syntax.
Ansible allows the following unchecked imports from these specific directories:
- ansible-core:
- For
lib/ansible/modules/
andlib/ansible/module_utils/
, unchecked imports are only allowed from the Python standard library; - For
lib/ansible/plugins/
, unchecked imports are only allowed from the Python standard library, from dependencies of ansible-core, and from ansible-core itself;
- For
- collections:
- For
plugins/modules/
andplugins/module_utils/
, unchecked imports are only allowed from the Python standard library; - For other directories in
plugins/
(see the community collection requirements for a list), unchecked imports are only allowed from the Python standard library, from dependencies of ansible-core, and from ansible-core itself.
- For