start getting modules to use shared import error code (#51787)

pull/51836/head
Jordan Borean 6 years ago committed by Sam Doran
parent 0924a8cf67
commit 0f0d33a954

@ -727,10 +727,13 @@ def jsonify(data, **kwargs):
raise UnicodeError('Invalid unicode encoding encountered') raise UnicodeError('Invalid unicode encoding encountered')
def missing_required_lib(library): def missing_required_lib(library, reason=None):
hostname = platform.node() hostname = platform.node()
return "Failed to import the required Python library (%s) on %s's Python %s. Please read module documentation " \ msg = "Failed to import the required Python library (%s) on %s's Python %s." % (library, hostname, sys.executable)
"and install in the appropriate location." % (library, hostname, sys.executable) if reason:
msg += " This is required %s." % reason
return msg + " Please read module documentation and install in the appropriate location"
class AnsibleFallbackNotFound(Exception): class AnsibleFallbackNotFound(Exception):

@ -5,18 +5,26 @@
from __future__ import absolute_import, division, print_function from __future__ import absolute_import, division, print_function
__metaclass__ = type __metaclass__ = type
import traceback
from ansible.module_utils.basic import missing_required_lib
REQUESTS_IMP_ERR = None
try: try:
import requests.exceptions import requests.exceptions
HAS_REQUESTS = True HAS_REQUESTS = True
except ImportError: except ImportError:
REQUESTS_IMP_ERR = traceback.format_exc()
HAS_REQUESTS = False HAS_REQUESTS = False
INFLUXDB_IMP_ERR = None
try: try:
from influxdb import InfluxDBClient from influxdb import InfluxDBClient
from influxdb import __version__ as influxdb_version from influxdb import __version__ as influxdb_version
from influxdb import exceptions from influxdb import exceptions
HAS_INFLUXDB = True HAS_INFLUXDB = True
except ImportError: except ImportError:
INFLUXDB_IMP_ERR = traceback.format_exc()
HAS_INFLUXDB = False HAS_INFLUXDB = False
@ -33,10 +41,10 @@ class InfluxDb():
def check_lib(self): def check_lib(self):
if not HAS_REQUESTS: if not HAS_REQUESTS:
self.module.fail_json(msg='This module requires "requests" module.') self.module.fail_json(msg=missing_required_lib('requests'), exception=REQUESTS_IMP_ERR)
if not HAS_INFLUXDB: if not HAS_INFLUXDB:
self.module.fail_json(msg='This module requires influxdb python package.') self.module.fail_json(msg=missing_required_lib('influxdb'), exception=INFLUXDB_IMP_ERR)
@staticmethod @staticmethod
def influxdb_argument_spec(): def influxdb_argument_spec():

@ -20,12 +20,15 @@ from __future__ import absolute_import, division, print_function
import copy import copy
import json import json
import os import os
import traceback
from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.basic import AnsibleModule, missing_required_lib
from ansible.module_utils.common.dict_transformations import recursive_diff from ansible.module_utils.common.dict_transformations import recursive_diff
from ansible.module_utils.six import iteritems, string_types from ansible.module_utils.six import iteritems, string_types
from ansible.module_utils._text import to_native
K8S_IMP_ERR = None
try: try:
import kubernetes import kubernetes
import openshift import openshift
@ -36,11 +39,14 @@ try:
except ImportError as e: except ImportError as e:
HAS_K8S_MODULE_HELPER = False HAS_K8S_MODULE_HELPER = False
k8s_import_exception = e k8s_import_exception = e
K8S_IMP_ERR = traceback.format_exc()
YAML_IMP_ERR = None
try: try:
import yaml import yaml
HAS_YAML = True HAS_YAML = True
except ImportError: except ImportError:
YAML_IMP_ERR = traceback.format_exc()
HAS_YAML = False HAS_YAML = False
try: try:
@ -244,11 +250,12 @@ class KubernetesAnsibleModule(AnsibleModule, K8sAnsibleMixin):
AnsibleModule.__init__(self, *args, **kwargs) AnsibleModule.__init__(self, *args, **kwargs)
if not HAS_K8S_MODULE_HELPER: if not HAS_K8S_MODULE_HELPER:
self.fail_json(msg="This module requires the OpenShift Python client. Try `pip install openshift`", error=str(k8s_import_exception)) self.fail_json(msg=missing_required_lib('openshift'), exception=K8S_IMP_ERR,
error=to_native(k8s_import_exception))
self.openshift_version = openshift.__version__ self.openshift_version = openshift.__version__
if not HAS_YAML: if not HAS_YAML:
self.fail_json(msg="This module requires PyYAML. Try `pip install PyYAML`") self.fail_json(msg=missing_required_lib("PyYAML"), exception=YAML_IMP_ERR)
def execute_module(self): def execute_module(self):
raise NotImplementedError() raise NotImplementedError()

@ -23,7 +23,9 @@ from datetime import datetime
from distutils.version import LooseVersion from distutils.version import LooseVersion
import time import time
import sys import sys
import traceback
from ansible.module_utils.basic import missing_required_lib
from ansible.module_utils.k8s.common import AUTH_ARG_SPEC, COMMON_ARG_SPEC from ansible.module_utils.k8s.common import AUTH_ARG_SPEC, COMMON_ARG_SPEC
from ansible.module_utils.six import string_types from ansible.module_utils.six import string_types
from ansible.module_utils.k8s.common import KubernetesAnsibleModule from ansible.module_utils.k8s.common import KubernetesAnsibleModule
@ -45,10 +47,12 @@ try:
except ImportError: except ImportError:
HAS_KUBERNETES_VALIDATE = False HAS_KUBERNETES_VALIDATE = False
K8S_CONFIG_HASH_IMP_ERR = None
try: try:
from openshift.helper.hashes import generate_hash from openshift.helper.hashes import generate_hash
HAS_K8S_CONFIG_HASH = True HAS_K8S_CONFIG_HASH = True
except ImportError: except ImportError:
K8S_CONFIG_HASH_IMP_ERR = traceback.format_exc()
HAS_K8S_CONFIG_HASH = False HAS_K8S_CONFIG_HASH = False
@ -97,10 +101,11 @@ class KubernetesRawModule(KubernetesAnsibleModule):
self.append_hash = self.params.get('append_hash') self.append_hash = self.params.get('append_hash')
if self.append_hash: if self.append_hash:
if not HAS_K8S_CONFIG_HASH: if not HAS_K8S_CONFIG_HASH:
self.fail_json(msg="openshift >= 0.7.2 is required for append_hash") self.fail_json(msg=missing_required_lib("openshift >= 0.7.2", reason="for append_hash"),
exception=K8S_CONFIG_HASH_IMP_ERR)
if self.params['merge_type']: if self.params['merge_type']:
if LooseVersion(self.openshift_version) < LooseVersion("0.6.2"): if LooseVersion(self.openshift_version) < LooseVersion("0.6.2"):
self.fail_json(msg="openshift >= 0.6.2 is required for merge_type") self.fail_json(msg=missing_required_lib("openshift >= 0.6.2", reason="for merge_type"))
if resource_definition: if resource_definition:
if isinstance(resource_definition, string_types): if isinstance(resource_definition, string_types):
try: try:

@ -8,18 +8,20 @@
from __future__ import absolute_import, division, print_function from __future__ import absolute_import, division, print_function
__metaclass__ = type __metaclass__ = type
from ansible.module_utils._text import to_native, to_text from ansible.module_utils._text import to_native
from ansible.module_utils.basic import env_fallback from ansible.module_utils.basic import missing_required_lib
from mimetypes import MimeTypes from mimetypes import MimeTypes
import json
import os import os
import traceback
PIKA_IMP_ERR = None
try: try:
import pika import pika
from pika import spec from pika import spec
HAS_PIKA = True HAS_PIKA = True
except ImportError: except ImportError:
PIKA_IMP_ERR = traceback.format_exc()
HAS_PIKA = False HAS_PIKA = False
@ -61,7 +63,7 @@ class RabbitClient():
def check_required_library(self): def check_required_library(self):
if not HAS_PIKA: if not HAS_PIKA:
self.module.fail_json(msg="Unable to find 'pika' Python library which is required.") self.module.fail_json(msg=missing_required_lib("pika"), exception=PIKA_IMP_ERR)
def check_host_params(self): def check_host_params(self):
# Fail if url is specified and other conflicting parameters have been specified # Fail if url is specified and other conflicting parameters have been specified

@ -72,13 +72,16 @@ old_value:
import traceback import traceback
from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.basic import AnsibleModule, missing_required_lib
from ansible.module_utils._text import to_native from ansible.module_utils._text import to_native
try: try:
import etcd3 import etcd3
etcd_found = True HAS_ETCD = True
except ImportError: except ImportError:
etcd_found = False ETCD_IMP_ERR = traceback.format_exc()
HAS_ETCD = False
def run_module(): def run_module():
@ -112,8 +115,8 @@ def run_module():
result['key'] = module.params.get('key') result['key'] = module.params.get('key')
if not etcd_found: if not HAS_ETCD:
module.fail_json(msg="the python etcd3 module is required") module.fail_json(msg=missing_required_lib('etcd3'), exception=ETCD_IMP_ERR)
allowed_keys = ['host', 'port', 'ca_cert', 'cert_key', 'cert_cert', allowed_keys = ['host', 'port', 'ca_cert', 'cert_key', 'cert_cert',
'timeout', 'user', 'password'] 'timeout', 'user', 'password']

@ -153,14 +153,17 @@ api_response:
import base64 import base64
import json import json
import traceback
YAML_IMP_ERR = None
try: try:
import yaml import yaml
HAS_LIB_YAML = True HAS_LIB_YAML = True
except ImportError: except ImportError:
YAML_IMP_ERR = traceback.format_exc()
HAS_LIB_YAML = False HAS_LIB_YAML = False
from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.basic import AnsibleModule, missing_required_lib
from ansible.module_utils.urls import fetch_url from ansible.module_utils.urls import fetch_url
@ -353,7 +356,7 @@ def main():
) )
if not HAS_LIB_YAML: if not HAS_LIB_YAML:
module.fail_json(msg="missing python library: yaml") module.fail_json(msg=missing_required_lib('PyYAML'), exception=YAML_IMP_ERR)
decode_cert_data(module) decode_cert_data(module)

@ -95,15 +95,18 @@ EXAMPLES = """
""" """
import time import time
import traceback
KAZOO_IMP_ERR = None
try: try:
from kazoo.client import KazooClient from kazoo.client import KazooClient
from kazoo.handlers.threading import KazooTimeoutError from kazoo.handlers.threading import KazooTimeoutError
KAZOO_INSTALLED = True KAZOO_INSTALLED = True
except ImportError: except ImportError:
KAZOO_IMP_ERR = traceback.format_exc()
KAZOO_INSTALLED = False KAZOO_INSTALLED = False
from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.basic import AnsibleModule, missing_required_lib
from ansible.module_utils._text import to_bytes from ansible.module_utils._text import to_bytes
@ -122,7 +125,7 @@ def main():
) )
if not KAZOO_INSTALLED: if not KAZOO_INSTALLED:
module.fail_json(msg='kazoo >= 2.1 is required to use this module. Use pip to install it.') module.fail_json(msg=missing_required_lib('kazoo >= 2.1'), exception=KAZOO_IMP_ERR)
check = check_params(module.params) check = check_params(module.params)
if not check['success']: if not check['success']:

@ -98,13 +98,15 @@ import datetime
import os import os
import traceback import traceback
PEXPECT_IMP_ERR = None
try: try:
import pexpect import pexpect
HAS_PEXPECT = True HAS_PEXPECT = True
except ImportError: except ImportError:
PEXPECT_IMP_ERR = traceback.format_exc()
HAS_PEXPECT = False HAS_PEXPECT = False
from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.basic import AnsibleModule, missing_required_lib
from ansible.module_utils._text import to_native, to_text from ansible.module_utils._text import to_native, to_text
@ -137,7 +139,8 @@ def main():
) )
if not HAS_PEXPECT: if not HAS_PEXPECT:
module.fail_json(msg='The pexpect python module is required') module.fail_json(msg=missing_required_lib("pexpect"),
exception=PEXPECT_IMP_ERR)
chdir = module.params['chdir'] chdir = module.params['chdir']
args = module.params['command'] args = module.params['command']

@ -125,13 +125,15 @@ from ansible.module_utils.acme import (
read_file, read_file,
) )
from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.basic import AnsibleModule, missing_required_lib
from ansible.module_utils._text import to_bytes, to_text from ansible.module_utils._text import to_bytes, to_text
import base64 import base64
import datetime import datetime
import sys import sys
import traceback
CRYPTOGRAPHY_IMP_ERR = None
try: try:
import cryptography import cryptography
import cryptography.hazmat.backends import cryptography.hazmat.backends
@ -147,6 +149,7 @@ try:
HAS_CRYPTOGRAPHY = (LooseVersion(cryptography.__version__) >= LooseVersion('1.3')) HAS_CRYPTOGRAPHY = (LooseVersion(cryptography.__version__) >= LooseVersion('1.3'))
_cryptography_backend = cryptography.hazmat.backends.default_backend() _cryptography_backend = cryptography.hazmat.backends.default_backend()
except ImportError as e: except ImportError as e:
CRYPTOGRAPHY_IMP_ERR = traceback.format_exc()
HAS_CRYPTOGRAPHY = False HAS_CRYPTOGRAPHY = False
@ -179,7 +182,7 @@ def main():
), ),
) )
if not HAS_CRYPTOGRAPHY: if not HAS_CRYPTOGRAPHY:
module.fail_json(msg='cryptography >= 1.3 is required for this module.') module.fail_json(msg=missing_required_lib('cryptography >= 1.3'), exception=CRYPTOGRAPHY_IMP_ERR)
try: try:
# Get parameters # Get parameters

@ -121,10 +121,12 @@ complete_chain:
''' '''
import os import os
import traceback
from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.basic import AnsibleModule, missing_required_lib
from ansible.module_utils._text import to_bytes from ansible.module_utils._text import to_bytes
CRYPTOGRAPHY_IMP_ERR = None
try: try:
import cryptography import cryptography
import cryptography.hazmat.backends import cryptography.hazmat.backends
@ -140,6 +142,7 @@ try:
HAS_CRYPTOGRAPHY = (LooseVersion(cryptography.__version__) >= LooseVersion('1.5')) HAS_CRYPTOGRAPHY = (LooseVersion(cryptography.__version__) >= LooseVersion('1.5'))
_cryptography_backend = cryptography.hazmat.backends.default_backend() _cryptography_backend = cryptography.hazmat.backends.default_backend()
except ImportError as e: except ImportError as e:
CRYPTOGRAPHY_IMP_ERR = traceback.format_exc()
HAS_CRYPTOGRAPHY = False HAS_CRYPTOGRAPHY = False
@ -289,7 +292,7 @@ def main():
) )
if not HAS_CRYPTOGRAPHY: if not HAS_CRYPTOGRAPHY:
module.fail_json(msg='cryptography >= 1.5 is required for this module.') module.fail_json(msg=missing_required_lib('cryptography >= 1.5'), exception=CRYPTOGRAPHY_IMP_ERR)
# Load chain # Load chain
chain = parse_PEM_list(module, module.params['input_chain'], source='input chain') chain = parse_PEM_list(module, module.params['input_chain'], source='input chain')

@ -107,15 +107,19 @@ EXAMPLES = '''
register: cert register: cert
''' '''
from ansible.module_utils.basic import AnsibleModule import traceback
from ansible.module_utils.basic import AnsibleModule, missing_required_lib
from os.path import isfile from os.path import isfile
from ssl import get_server_certificate from ssl import get_server_certificate
from socket import setdefaulttimeout from socket import setdefaulttimeout
PYOPENSSL_IMP_ERR = None
try: try:
from OpenSSL import crypto from OpenSSL import crypto
except ImportError: except ImportError:
PYOPENSSL_IMP_ERR = traceback.format_exc()
pyopenssl_found = False pyopenssl_found = False
else: else:
pyopenssl_found = True pyopenssl_found = True
@ -141,7 +145,7 @@ def main():
) )
if not pyopenssl_found: if not pyopenssl_found:
module.fail_json(msg='the python pyOpenSSL module is required') module.fail_json(msg=missing_required_lib('pyOpenSSL'), exception=PYOPENSSL_IMP_ERR)
if timeout: if timeout:
setdefaulttimeout(timeout) setdefaulttimeout(timeout)

@ -418,15 +418,18 @@ filename:
from random import randint from random import randint
import datetime import datetime
import os import os
import traceback
from ansible.module_utils import crypto as crypto_utils from ansible.module_utils import crypto as crypto_utils
from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.basic import AnsibleModule, missing_required_lib
from ansible.module_utils._text import to_native, to_bytes from ansible.module_utils._text import to_native, to_bytes
PYOPENSSL_IMP_ERR = None
try: try:
import OpenSSL import OpenSSL
from OpenSSL import crypto from OpenSSL import crypto
except ImportError: except ImportError:
PYOPENSSL_IMP_ERR = traceback.format_exc()
pyopenssl_found = False pyopenssl_found = False
else: else:
pyopenssl_found = True pyopenssl_found = True
@ -1052,7 +1055,7 @@ def main():
) )
if not pyopenssl_found: if not pyopenssl_found:
module.fail_json(msg='The python pyOpenSSL library is required') module.fail_json(msg=missing_required_lib('pyOpenSSL'), exception=PYOPENSSL_IMP_ERR)
if module.params['provider'] in ['selfsigned', 'ownca', 'assertonly']: if module.params['provider'] in ['selfsigned', 'ownca', 'assertonly']:
try: try:
getattr(crypto.X509Req, 'get_extensions') getattr(crypto.X509Req, 'get_extensions')

@ -319,20 +319,23 @@ ocsp_must_staple:
import abc import abc
import os import os
import traceback
from distutils.version import LooseVersion from distutils.version import LooseVersion
from ansible.module_utils import crypto as crypto_utils from ansible.module_utils import crypto as crypto_utils
from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.basic import AnsibleModule, missing_required_lib
from ansible.module_utils._text import to_native, to_bytes, to_text from ansible.module_utils._text import to_native, to_bytes, to_text
MINIMAL_PYOPENSSL_VERSION = '0.15' MINIMAL_PYOPENSSL_VERSION = '0.15'
MINIMAL_CRYPTOGRAPHY_VERSION = '1.3' MINIMAL_CRYPTOGRAPHY_VERSION = '1.3'
PYOPENSSL_IMP_ERR = None
try: try:
import OpenSSL import OpenSSL
from OpenSSL import crypto from OpenSSL import crypto
PYOPENSSL_VERSION = LooseVersion(OpenSSL.__version__) PYOPENSSL_VERSION = LooseVersion(OpenSSL.__version__)
except ImportError: except ImportError:
PYOPENSSL_IMP_ERR = traceback.format_exc()
PYOPENSSL_FOUND = False PYOPENSSL_FOUND = False
else: else:
PYOPENSSL_FOUND = True PYOPENSSL_FOUND = True
@ -345,6 +348,7 @@ else:
OPENSSL_MUST_STAPLE_NAME = b"1.3.6.1.5.5.7.1.24" OPENSSL_MUST_STAPLE_NAME = b"1.3.6.1.5.5.7.1.24"
OPENSSL_MUST_STAPLE_VALUE = b"DER:30:03:02:01:05" OPENSSL_MUST_STAPLE_VALUE = b"DER:30:03:02:01:05"
CRYPTOGRAPHY_IMP_ERR = None
try: try:
import cryptography import cryptography
import cryptography.x509 import cryptography.x509
@ -355,6 +359,7 @@ try:
import cryptography.hazmat.primitives.hashes import cryptography.hazmat.primitives.hashes
CRYPTOGRAPHY_VERSION = LooseVersion(cryptography.__version__) CRYPTOGRAPHY_VERSION = LooseVersion(cryptography.__version__)
except ImportError: except ImportError:
CRYPTOGRAPHY_IMP_ERR = traceback.format_exc()
CRYPTOGRAPHY_FOUND = False CRYPTOGRAPHY_FOUND = False
else: else:
CRYPTOGRAPHY_FOUND = True CRYPTOGRAPHY_FOUND = True
@ -995,7 +1000,7 @@ def main():
MINIMAL_PYOPENSSL_VERSION)) MINIMAL_PYOPENSSL_VERSION))
if backend == 'pyopenssl': if backend == 'pyopenssl':
if not PYOPENSSL_FOUND: if not PYOPENSSL_FOUND:
module.fail_json(msg='The Python pyOpenSSL library is required') module.fail_json(msg=missing_required_lib('pyOpenSSL'), exception=PYOPENSSL_IMP_ERR)
try: try:
getattr(crypto.X509Req, 'get_extensions') getattr(crypto.X509Req, 'get_extensions')
except AttributeError: except AttributeError:
@ -1003,7 +1008,7 @@ def main():
csr = CertificateSigningRequestPyOpenSSL(module) csr = CertificateSigningRequestPyOpenSSL(module)
elif backend == 'cryptography': elif backend == 'cryptography':
if not CRYPTOGRAPHY_FOUND: if not CRYPTOGRAPHY_FOUND:
module.fail_json(msg='The Python cryptography library is required') module.fail_json(msg=missing_required_lib('cryptography'), exception=CRYPTOGRAPHY_IMP_ERR)
csr = CertificateSigningRequestCryptography(module) csr = CertificateSigningRequestCryptography(module)
if module.params['state'] == 'present': if module.params['state'] == 'present':

@ -140,15 +140,18 @@ privatekey:
import stat import stat
import os import os
import traceback
PYOPENSSL_IMP_ERR = None
try: try:
from OpenSSL import crypto from OpenSSL import crypto
except ImportError: except ImportError:
PYOPENSSL_IMP_ERR = traceback.format_exc()
pyopenssl_found = False pyopenssl_found = False
else: else:
pyopenssl_found = True pyopenssl_found = True
from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.basic import AnsibleModule, missing_required_lib
from ansible.module_utils import crypto as crypto_utils from ansible.module_utils import crypto as crypto_utils
from ansible.module_utils._text import to_bytes, to_native from ansible.module_utils._text import to_bytes, to_native
@ -311,7 +314,7 @@ def main():
) )
if not pyopenssl_found: if not pyopenssl_found:
module.fail_json(msg='The python pyOpenSSL library is required') module.fail_json(msg=missing_required_lib('pyOpenSSL'), exception=PYOPENSSL_IMP_ERR)
base_dir = os.path.dirname(module.params['path']) or '.' base_dir = os.path.dirname(module.params['path']) or '.'
if not os.path.isdir(base_dir): if not os.path.isdir(base_dir):

@ -198,14 +198,18 @@ from distutils.version import LooseVersion
MINIMAL_PYOPENSSL_VERSION = '0.6' MINIMAL_PYOPENSSL_VERSION = '0.6'
MINIMAL_CRYPTOGRAPHY_VERSION = '1.2.3' MINIMAL_CRYPTOGRAPHY_VERSION = '1.2.3'
PYOPENSSL_IMP_ERR = None
try: try:
import OpenSSL import OpenSSL
from OpenSSL import crypto from OpenSSL import crypto
PYOPENSSL_VERSION = LooseVersion(OpenSSL.__version__) PYOPENSSL_VERSION = LooseVersion(OpenSSL.__version__)
except ImportError: except ImportError:
PYOPENSSL_IMP_ERR = traceback.format_exc()
PYOPENSSL_FOUND = False PYOPENSSL_FOUND = False
else: else:
PYOPENSSL_FOUND = True PYOPENSSL_FOUND = True
CRYPTOGRAPHY_IMP_ERR = None
try: try:
import cryptography import cryptography
import cryptography.exceptions import cryptography.exceptions
@ -217,6 +221,7 @@ try:
import cryptography.hazmat.primitives.asymmetric.utils import cryptography.hazmat.primitives.asymmetric.utils
CRYPTOGRAPHY_VERSION = LooseVersion(cryptography.__version__) CRYPTOGRAPHY_VERSION = LooseVersion(cryptography.__version__)
except ImportError: except ImportError:
CRYPTOGRAPHY_IMP_ERR = traceback.format_exc()
CRYPTOGRAPHY_FOUND = False CRYPTOGRAPHY_FOUND = False
else: else:
CRYPTOGRAPHY_FOUND = True CRYPTOGRAPHY_FOUND = True
@ -233,7 +238,7 @@ else:
from ansible.module_utils import crypto as crypto_utils from ansible.module_utils import crypto as crypto_utils
from ansible.module_utils._text import to_native, to_bytes from ansible.module_utils._text import to_native, to_bytes
from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.basic import AnsibleModule, missing_required_lib
from ansible.module_utils.six import string_types from ansible.module_utils.six import string_types
@ -617,11 +622,11 @@ def main():
MINIMAL_PYOPENSSL_VERSION)) MINIMAL_PYOPENSSL_VERSION))
if backend == 'pyopenssl': if backend == 'pyopenssl':
if not PYOPENSSL_FOUND: if not PYOPENSSL_FOUND:
module.fail_json(msg='The Python pyOpenSSL library is required') module.fail_json(msg=missing_required_lib('pyOpenSSL'), exception=PYOPENSSL_IMP_ERR)
private_key = PrivateKeyPyOpenSSL(module) private_key = PrivateKeyPyOpenSSL(module)
elif backend == 'cryptography': elif backend == 'cryptography':
if not CRYPTOGRAPHY_FOUND: if not CRYPTOGRAPHY_FOUND:
module.fail_json(msg='The Python cryptography library is required') module.fail_json(msg=missing_required_lib('cryptography'), exception=CRYPTOGRAPHY_IMP_ERR)
private_key = PrivateKeyCryptography(module) private_key = PrivateKeyCryptography(module)
if private_key.state == 'present': if private_key.state == 'present':

@ -125,19 +125,22 @@ fingerprint:
import hashlib import hashlib
import os import os
import traceback
PYOPENSSL_IMP_ERR = None
try: try:
from OpenSSL import crypto from OpenSSL import crypto
from cryptography.hazmat.backends import default_backend from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import serialization as crypto_serialization from cryptography.hazmat.primitives import serialization as crypto_serialization
except ImportError: except ImportError:
PYOPENSSL_IMP_ERR = traceback.format_exc()
pyopenssl_found = False pyopenssl_found = False
else: else:
pyopenssl_found = True pyopenssl_found = True
from ansible.module_utils import crypto as crypto_utils from ansible.module_utils import crypto as crypto_utils
from ansible.module_utils._text import to_native from ansible.module_utils._text import to_native
from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.basic import AnsibleModule, missing_required_lib
class PublicKeyError(crypto_utils.OpenSSLObjectError): class PublicKeyError(crypto_utils.OpenSSLObjectError):
@ -269,7 +272,7 @@ def main():
) )
if not pyopenssl_found: if not pyopenssl_found:
module.fail_json(msg='the python pyOpenSSL module is required') module.fail_json(msg=missing_required_lib('pyOpenSSL'), exception=PYOPENSSL_IMP_ERR)
base_dir = os.path.dirname(module.params['path']) or '.' base_dir = os.path.dirname(module.params['path']) or '.'
if not os.path.isdir(base_dir): if not os.path.isdir(base_dir):

@ -169,15 +169,18 @@ RETURN = '''
# Returns only a success/failure result. Changed is always false. # Returns only a success/failure result. Changed is always false.
''' '''
from ansible.module_utils.basic import AnsibleModule import traceback
from ansible.module_utils.basic import AnsibleModule, missing_required_lib
LIB_FOUND_ERR = None
try: try:
import aerospike import aerospike
from time import sleep from time import sleep
import re import re
except ImportError as ie: except ImportError as ie:
LIB_FOUND = False LIB_FOUND = False
LIB_FOUND_ERR = ie LIB_FOUND_ERR = traceback.format_exc()
else: else:
LIB_FOUND = True LIB_FOUND = True
@ -210,13 +213,8 @@ def run_module():
supports_check_mode=True supports_check_mode=True
) )
if not LIB_FOUND: if not LIB_FOUND:
module.fail_json( module.fail_json(msg=missing_required_lib('aerospike'),
msg="A required module was not found. This playbook" + exception=LIB_FOUND_ERR)
" requires the 'aerospike' 'time' and 're' modules. " +
"Please run 'pip install aerospike'. The other modules" +
" should be included in a basic python install." +
" OS Error: {0}".format(LIB_FOUND_ERR)
)
try: try:
if module.check_mode: if module.check_mode:

@ -117,14 +117,16 @@ EXAMPLES = '''
import traceback import traceback
REDIS_IMP_ERR = None
try: try:
import redis import redis
except ImportError: except ImportError:
REDIS_IMP_ERR = traceback.format_exc()
redis_found = False redis_found = False
else: else:
redis_found = True redis_found = True
from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.basic import AnsibleModule, missing_required_lib
from ansible.module_utils._text import to_native from ansible.module_utils._text import to_native
@ -174,7 +176,7 @@ def main():
) )
if not redis_found: if not redis_found:
module.fail_json(msg="python redis module is required") module.fail_json(msg=missing_required_lib('redis'), exception=REDIS_IMP_ERR)
login_password = module.params['login_password'] login_password = module.params['login_password']
login_host = module.params['login_host'] login_host = module.params['login_host']

@ -110,7 +110,7 @@ except ImportError:
else: else:
pymongo_found = True pymongo_found = True
from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.basic import AnsibleModule, missing_required_lib
from ansible.module_utils.six.moves import configparser from ansible.module_utils.six.moves import configparser
from ansible.module_utils._text import to_native from ansible.module_utils._text import to_native
@ -156,7 +156,7 @@ def main():
) )
if not pymongo_found: if not pymongo_found:
module.fail_json(msg='the python pymongo module is required') module.fail_json(msg=missing_required_lib('pymongo'))
login_user = module.params['login_user'] login_user = module.params['login_user']
login_password = module.params['login_password'] login_password = module.params['login_password']

@ -140,7 +140,7 @@ except ImportError:
else: else:
pymongo_found = True pymongo_found = True
from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.basic import AnsibleModule, missing_required_lib
from ansible.module_utils.six import binary_type, text_type from ansible.module_utils.six import binary_type, text_type
from ansible.module_utils.six.moves import configparser from ansible.module_utils.six.moves import configparser
from ansible.module_utils._text import to_native from ansible.module_utils._text import to_native
@ -243,7 +243,7 @@ def main():
supports_check_mode=True) supports_check_mode=True)
if not pymongo_found: if not pymongo_found:
module.fail_json(msg='the python pymongo module is required') module.fail_json(msg=missing_required_lib('pymongo'))
login_user = module.params['login_user'] login_user = module.params['login_user']
login_password = module.params['login_password'] login_password = module.params['login_password']

@ -194,7 +194,7 @@ except ImportError:
else: else:
pymongo_found = True pymongo_found = True
from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.basic import AnsibleModule, missing_required_lib
from ansible.module_utils.six import binary_type, text_type from ansible.module_utils.six import binary_type, text_type
from ansible.module_utils.six.moves import configparser from ansible.module_utils.six.moves import configparser
from ansible.module_utils._text import to_native from ansible.module_utils._text import to_native
@ -350,7 +350,7 @@ def main():
) )
if not pymongo_found: if not pymongo_found:
module.fail_json(msg='the python pymongo module is required') module.fail_json(msg=missing_required_lib('pymongo'))
login_user = module.params['login_user'] login_user = module.params['login_user']
login_password = module.params['login_password'] login_password = module.params['login_password']

@ -86,15 +86,18 @@ RETURN = '''
''' '''
import os import os
import traceback
PYMSSQL_IMP_ERR = None
try: try:
import pymssql import pymssql
except ImportError: except ImportError:
PYMSSQL_IMP_ERR = traceback.format_exc()
mssql_found = False mssql_found = False
else: else:
mssql_found = True mssql_found = True
from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.basic import AnsibleModule, missing_required_lib
def db_exists(conn, cursor, db): def db_exists(conn, cursor, db):
@ -155,7 +158,7 @@ def main():
) )
if not mssql_found: if not mssql_found:
module.fail_json(msg="pymssql python module is required") module.fail_json(msg=missing_required_lib('pymssql'), exception=PYMSSQL_IMP_ERR)
db = module.params['name'] db = module.params['name']
state = module.params['state'] state = module.params['state']

@ -115,16 +115,18 @@ import pipes
import subprocess import subprocess
import traceback import traceback
PSYCOPG2_IMP_ERR = None
try: try:
import psycopg2 import psycopg2
import psycopg2.extras import psycopg2.extras
except ImportError: except ImportError:
PSYCOPG2_IMP_ERR = traceback.format_exc()
HAS_PSYCOPG2 = False HAS_PSYCOPG2 = False
else: else:
HAS_PSYCOPG2 = True HAS_PSYCOPG2 = True
import ansible.module_utils.postgres as pgutils import ansible.module_utils.postgres as pgutils
from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.basic import AnsibleModule, missing_required_lib
from ansible.module_utils.database import SQLParseError, pg_quote_identifier from ansible.module_utils.database import SQLParseError, pg_quote_identifier
from ansible.module_utils.six import iteritems from ansible.module_utils.six import iteritems
from ansible.module_utils._text import to_native from ansible.module_utils._text import to_native
@ -384,7 +386,7 @@ def main():
) )
if not HAS_PSYCOPG2: if not HAS_PSYCOPG2:
module.fail_json(msg="the python psycopg2 module is required") module.fail_json(msg=missing_required_lib('psycopg2'), exception=PSYCOPG2_IMP_ERR)
db = module.params["db"] db = module.params["db"]
owner = module.params["owner"] owner = module.params["owner"]

@ -110,15 +110,17 @@ EXAMPLES = '''
''' '''
import traceback import traceback
PSYCOPG2_IMP_ERR = None
try: try:
import psycopg2 import psycopg2
import psycopg2.extras import psycopg2.extras
except ImportError: except ImportError:
PSYCOPG2_IMP_ERR = traceback.format_exc()
postgresqldb_found = False postgresqldb_found = False
else: else:
postgresqldb_found = True postgresqldb_found = True
from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.basic import AnsibleModule, missing_required_lib
from ansible.module_utils.six import iteritems from ansible.module_utils.six import iteritems
from ansible.module_utils._text import to_native from ansible.module_utils._text import to_native
from ansible.module_utils.database import pg_quote_identifier from ansible.module_utils.database import pg_quote_identifier
@ -188,7 +190,7 @@ def main():
) )
if not postgresqldb_found: if not postgresqldb_found:
module.fail_json(msg="the python psycopg2 module is required") module.fail_json(msg=missing_required_lib('psycopg2'), exception=PSYCOPG2_IMP_ERR)
db = module.params["db"] db = module.params["db"]
ext = module.params["ext"] ext = module.params["ext"]

@ -155,16 +155,18 @@ RETURN = ''' # '''
import traceback import traceback
PSYCOPG2_IMP_ERR = None
try: try:
import psycopg2 import psycopg2
import psycopg2.extras import psycopg2.extras
except ImportError: except ImportError:
PSYCOPG2_IMP_ERR = traceback.format_exc()
postgresqldb_found = False postgresqldb_found = False
else: else:
postgresqldb_found = True postgresqldb_found = True
import ansible.module_utils.postgres as pgutils import ansible.module_utils.postgres as pgutils
from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.basic import AnsibleModule, missing_required_lib
from ansible.module_utils.database import SQLParseError from ansible.module_utils.database import SQLParseError
from ansible.module_utils._text import to_native from ansible.module_utils._text import to_native
from ansible.module_utils.six import iteritems from ansible.module_utils.six import iteritems
@ -320,7 +322,7 @@ def main():
"make sense to pass an index type" % idxname) "make sense to pass an index type" % idxname)
if not postgresqldb_found: if not postgresqldb_found:
module.fail_json(msg="the python psycopg2 module is required") module.fail_json(msg=missing_required_lib('psycopg2'), exception=PSYCOPG2_IMP_ERR)
# To use defaults values, keyword arguments must be absent, so # To use defaults values, keyword arguments must be absent, so
# check which values are empty and don't include in the **kw # check which values are empty and don't include in the **kw

@ -158,14 +158,16 @@ EXAMPLES = '''
''' '''
import traceback import traceback
PSYCOPG2_IMP_ERR = None
try: try:
import psycopg2 import psycopg2
except ImportError: except ImportError:
PSYCOPG2_IMP_ERR = traceback.format_exc()
postgresqldb_found = False postgresqldb_found = False
else: else:
postgresqldb_found = True postgresqldb_found = True
from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.basic import AnsibleModule, missing_required_lib
from ansible.module_utils.six import iteritems from ansible.module_utils.six import iteritems
from ansible.module_utils._text import to_native from ansible.module_utils._text import to_native
from ansible.module_utils.database import pg_quote_identifier from ansible.module_utils.database import pg_quote_identifier
@ -252,7 +254,7 @@ def main():
session_role = module.params["session_role"] session_role = module.params["session_role"]
if not postgresqldb_found: if not postgresqldb_found:
module.fail_json(msg="the python psycopg2 module is required") module.fail_json(msg=missing_required_lib('psycopg2'), exception=PSYCOPG2_IMP_ERR)
# To use defaults values, keyword arguments must be absent, so # To use defaults values, keyword arguments must be absent, so
# check which values are empty and don't include in the **kw # check which values are empty and don't include in the **kw

@ -269,14 +269,16 @@ EXAMPLES = """
import traceback import traceback
PSYCOPG2_IMP_ERR = None
try: try:
import psycopg2 import psycopg2
import psycopg2.extensions import psycopg2.extensions
except ImportError: except ImportError:
PSYCOPG2_IMP_ERR = traceback.format_exc()
psycopg2 = None psycopg2 = None
# import module snippets # import module snippets
from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.basic import AnsibleModule, missing_required_lib
from ansible.module_utils.database import pg_quote_identifier from ansible.module_utils.database import pg_quote_identifier
from ansible.module_utils._text import to_native from ansible.module_utils._text import to_native
@ -715,7 +717,7 @@ def main():
# Connect to Database # Connect to Database
if not psycopg2: if not psycopg2:
module.fail_json(msg='Python module "psycopg2" must be installed.') module.fail_json(msg=missing_required_lib('psycopg2'), exception=PSYCOPG2_IMP_ERR)
try: try:
conn = Connection(p) conn = Connection(p)
except psycopg2.Error as e: except psycopg2.Error as e:

@ -119,15 +119,17 @@ schema:
import traceback import traceback
PSYCOPG2_IMP_ERR = None
try: try:
import psycopg2 import psycopg2
import psycopg2.extras import psycopg2.extras
except ImportError: except ImportError:
PSYCOPG2_IMP_ERR = traceback.format_exc()
postgresqldb_found = False postgresqldb_found = False
else: else:
postgresqldb_found = True postgresqldb_found = True
from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.basic import AnsibleModule, missing_required_lib
from ansible.module_utils.database import SQLParseError, pg_quote_identifier from ansible.module_utils.database import SQLParseError, pg_quote_identifier
from ansible.module_utils.six import iteritems from ansible.module_utils.six import iteritems
from ansible.module_utils._text import to_native from ansible.module_utils._text import to_native
@ -229,7 +231,7 @@ def main():
) )
if not postgresqldb_found: if not postgresqldb_found:
module.fail_json(msg="the python psycopg2 module is required") module.fail_json(msg=missing_required_lib('psycopg2'), exception=PSYCOPG2_IMP_ERR)
schema = module.params["schema"] schema = module.params["schema"]
owner = module.params["owner"] owner = module.params["owner"]

@ -223,16 +223,18 @@ import re
import traceback import traceback
from hashlib import md5 from hashlib import md5
PSYCOPG2_IMP_ERR = None
try: try:
import psycopg2 import psycopg2
import psycopg2.extras import psycopg2.extras
except ImportError: except ImportError:
PSYCOPG2_IMP_ERR = traceback.format_exc()
postgresqldb_found = False postgresqldb_found = False
else: else:
postgresqldb_found = True postgresqldb_found = True
import ansible.module_utils.postgres as pgutils import ansible.module_utils.postgres as pgutils
from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.basic import AnsibleModule, missing_required_lib
from ansible.module_utils.database import pg_quote_identifier, SQLParseError from ansible.module_utils.database import pg_quote_identifier, SQLParseError
from ansible.module_utils._text import to_bytes, to_native from ansible.module_utils._text import to_bytes, to_native
from ansible.module_utils.six import iteritems from ansible.module_utils.six import iteritems
@ -785,7 +787,7 @@ def main():
conn_limit = module.params["conn_limit"] conn_limit = module.params["conn_limit"]
if not postgresqldb_found: if not postgresqldb_found:
module.fail_json(msg="the python psycopg2 module is required") module.fail_json(msg=missing_required_lib('psycopg2'), exception=PSYCOPG2_IMP_ERR)
# To use defaults values, keyword arguments must be absent, so # To use defaults values, keyword arguments must be absent, so
# check which values are empty and don't include in the **kw # check which values are empty and don't include in the **kw

@ -66,14 +66,16 @@ EXAMPLES = """
""" """
import traceback import traceback
PYODBC_IMP_ERR = None
try: try:
import pyodbc import pyodbc
except ImportError: except ImportError:
PYODBC_IMP_ERR = traceback.format_exc()
pyodbc_found = False pyodbc_found = False
else: else:
pyodbc_found = True pyodbc_found = True
from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.basic import AnsibleModule, missing_required_lib
from ansible.module_utils._text import to_native from ansible.module_utils._text import to_native
@ -141,7 +143,7 @@ def main():
), supports_check_mode=True) ), supports_check_mode=True)
if not pyodbc_found: if not pyodbc_found:
module.fail_json(msg="The python pyodbc module is required.") module.fail_json(msg=missing_required_lib('pyodbc'), exception=PYODBC_IMP_ERR)
parameter_name = module.params['parameter'] parameter_name = module.params['parameter']
current_value = module.params['value'] current_value = module.params['value']

@ -58,14 +58,16 @@ EXAMPLES = """
""" """
import traceback import traceback
PYODBC_IMP_ERR = None
try: try:
import pyodbc import pyodbc
except ImportError: except ImportError:
PYODBC_IMP_ERR = traceback.format_exc()
pyodbc_found = False pyodbc_found = False
else: else:
pyodbc_found = True pyodbc_found = True
from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.basic import AnsibleModule, missing_required_lib
from ansible.module_utils._text import to_native from ansible.module_utils._text import to_native
@ -227,7 +229,7 @@ def main():
), supports_check_mode=True) ), supports_check_mode=True)
if not pyodbc_found: if not pyodbc_found:
module.fail_json(msg="The python pyodbc module is required.") module.fail_json(msg=missing_required_lib('pyodbc'), exception=PYODBC_IMP_ERR)
db = '' db = ''
if module.params['db']: if module.params['db']:

@ -74,14 +74,16 @@ EXAMPLES = """
""" """
import traceback import traceback
PYODBC_IMP_ERR = None
try: try:
import pyodbc import pyodbc
except ImportError: except ImportError:
PYODBC_IMP_ERR = traceback.format_exc()
pyodbc_found = False pyodbc_found = False
else: else:
pyodbc_found = True pyodbc_found = True
from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.basic import AnsibleModule, missing_required_lib
from ansible.module_utils._text import to_native from ansible.module_utils._text import to_native
@ -180,7 +182,7 @@ def main():
), supports_check_mode=True) ), supports_check_mode=True)
if not pyodbc_found: if not pyodbc_found:
module.fail_json(msg="The python pyodbc module is required.") module.fail_json(msg=missing_required_lib('pyodbc'), exception=PYODBC_IMP_ERR)
role = module.params['role'] role = module.params['role']
assigned_roles = [] assigned_roles = []

@ -94,14 +94,16 @@ EXAMPLES = """
""" """
import traceback import traceback
PYODBC_IMP_ERR = None
try: try:
import pyodbc import pyodbc
except ImportError: except ImportError:
PYODBC_IMP_ERR = traceback.format_exc()
pyodbc_found = False pyodbc_found = False
else: else:
pyodbc_found = True pyodbc_found = True
from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.basic import AnsibleModule, missing_required_lib
from ansible.module_utils._text import to_native from ansible.module_utils._text import to_native
@ -246,7 +248,7 @@ def main():
), supports_check_mode=True) ), supports_check_mode=True)
if not pyodbc_found: if not pyodbc_found:
module.fail_json(msg="The python pyodbc module is required.") module.fail_json(msg=missing_required_lib('pyodbc'), exception=PYODBC_IMP_ERR)
schema = module.params['schema'] schema = module.params['schema']
usage_roles = [] usage_roles = []

@ -102,14 +102,16 @@ EXAMPLES = """
""" """
import traceback import traceback
PYODBC_IMP_ERR = None
try: try:
import pyodbc import pyodbc
except ImportError: except ImportError:
PYODBC_IMP_ERR = traceback.format_exc()
pyodbc_found = False pyodbc_found = False
else: else:
pyodbc_found = True pyodbc_found = True
from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.basic import AnsibleModule, missing_required_lib
from ansible.module_utils._text import to_native from ansible.module_utils._text import to_native
@ -301,7 +303,7 @@ def main():
), supports_check_mode=True) ), supports_check_mode=True)
if not pyodbc_found: if not pyodbc_found:
module.fail_json(msg="The python pyodbc module is required.") module.fail_json(msg=missing_required_lib('pyodbc'), exception=PYODBC_IMP_ERR)
user = module.params['user'] user = module.params['user']
profile = module.params['profile'] profile = module.params['profile']

@ -151,21 +151,25 @@ import tarfile
import zipfile import zipfile
from traceback import format_exc from traceback import format_exc
from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.basic import AnsibleModule, missing_required_lib
from ansible.module_utils._text import to_native from ansible.module_utils._text import to_native
from ansible.module_utils.six import PY3 from ansible.module_utils.six import PY3
LZMA_IMP_ERR = None
if PY3: if PY3:
try: try:
import lzma import lzma
HAS_LZMA = True HAS_LZMA = True
except ImportError: except ImportError:
LZMA_IMP_ERR = format_exc()
HAS_LZMA = False HAS_LZMA = False
else: else:
try: try:
from backports import lzma from backports import lzma
HAS_LZMA = True HAS_LZMA = True
except ImportError: except ImportError:
LZMA_IMP_ERR = format_exc()
HAS_LZMA = False HAS_LZMA = False
@ -202,6 +206,8 @@ def main():
# Fail early # Fail early
if not HAS_LZMA and format == 'xz': if not HAS_LZMA and format == 'xz':
module.fail_json(msg=missing_required_lib("lzma or backports.lzma", reason="when using xz format"),
exception=LZMA_IMP_ERR)
module.fail_json(msg="lzma or backports.lzma is required when using xz format.") module.fail_json(msg="lzma or backports.lzma is required when using xz format.")
for path in paths: for path in paths:

@ -335,13 +335,15 @@ import traceback
from distutils.version import LooseVersion from distutils.version import LooseVersion
from io import BytesIO from io import BytesIO
LXML_IMP_ERR = None
try: try:
from lxml import etree, objectify from lxml import etree, objectify
HAS_LXML = True HAS_LXML = True
except ImportError: except ImportError:
LXML_IMP_ERR = traceback.format_exc()
HAS_LXML = False HAS_LXML = False
from ansible.module_utils.basic import AnsibleModule, json_dict_bytes_to_unicode from ansible.module_utils.basic import AnsibleModule, json_dict_bytes_to_unicode, missing_required_lib
from ansible.module_utils.six import iteritems, string_types from ansible.module_utils.six import iteritems, string_types
from ansible.module_utils._text import to_bytes, to_native from ansible.module_utils._text import to_bytes, to_native
from ansible.module_utils.common._collections_compat import MutableMapping from ansible.module_utils.common._collections_compat import MutableMapping
@ -876,7 +878,7 @@ def main():
# Check if we have lxml 2.3.0 or newer installed # Check if we have lxml 2.3.0 or newer installed
if not HAS_LXML: if not HAS_LXML:
module.fail_json(msg='The xml ansible module requires the lxml python library installed on the managed machine') module.fail_json(msg=missing_required_lib("lxml"), exception=LXML_IMP_ERR)
elif LooseVersion('.'.join(to_native(f) for f in etree.LXML_VERSION)) < LooseVersion('2.3.0'): elif LooseVersion('.'.join(to_native(f) for f in etree.LXML_VERSION)) < LooseVersion('2.3.0'):
module.fail_json(msg='The xml ansible module requires lxml 2.3.0 or newer installed on the managed machine') module.fail_json(msg='The xml ansible module requires lxml 2.3.0 or newer installed on the managed machine')
elif LooseVersion('.'.join(to_native(f) for f in etree.LXML_VERSION)) < LooseVersion('3.0.0'): elif LooseVersion('.'.join(to_native(f) for f in etree.LXML_VERSION)) < LooseVersion('3.0.0'):

@ -75,16 +75,18 @@ EXAMPLES = '''
''' '''
import json import json
import traceback
REQUESTS_IMP_ERR = None
try: try:
import requests import requests
HAS_REQUESTS = True HAS_REQUESTS = True
except ImportError: except ImportError:
REQUESTS_IMP_ERR = traceback.format_exc()
HAS_REQUESTS = False HAS_REQUESTS = False
from ansible.module_utils.six.moves.urllib import parse as urllib_parse from ansible.module_utils.six.moves.urllib import parse as urllib_parse
from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.basic import AnsibleModule, missing_required_lib
from ansible.module_utils.rabbitmq import rabbitmq_argument_spec from ansible.module_utils.rabbitmq import rabbitmq_argument_spec
@ -286,7 +288,7 @@ def main():
module = AnsibleModule(argument_spec=argument_spec, supports_check_mode=True) module = AnsibleModule(argument_spec=argument_spec, supports_check_mode=True)
if not HAS_REQUESTS: if not HAS_REQUESTS:
module.fail_json(msg="requests library is required for this module. To install, use `pip install requests`") module.fail_json(msg=missing_required_lib("requests"), exception=REQUESTS_IMP_ERR)
RabbitMqBinding(module).run() RabbitMqBinding(module).run()

@ -81,14 +81,17 @@ EXAMPLES = '''
''' '''
import json import json
import traceback
REQUESTS_IMP_ERR = None
try: try:
import requests import requests
HAS_REQUESTS = True HAS_REQUESTS = True
except ImportError: except ImportError:
REQUESTS_IMP_ERR = traceback.format_exc()
HAS_REQUESTS = False HAS_REQUESTS = False
from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.basic import AnsibleModule, missing_required_lib
from ansible.module_utils.six.moves.urllib import parse as urllib_parse from ansible.module_utils.six.moves.urllib import parse as urllib_parse
from ansible.module_utils.rabbitmq import rabbitmq_argument_spec from ansible.module_utils.rabbitmq import rabbitmq_argument_spec
@ -118,7 +121,7 @@ def main():
) )
if not HAS_REQUESTS: if not HAS_REQUESTS:
module.fail_json(msg="requests library is required for this module. To install, use `pip install requests`") module.fail_json(msg=missing_required_lib("requests"), exception=REQUESTS_IMP_ERR)
result = dict(changed=False, name=module.params['name']) result = dict(changed=False, name=module.params['name'])

@ -91,14 +91,17 @@ EXAMPLES = '''
''' '''
import json import json
import traceback
REQUESTS_IMP_ERR = None
try: try:
import requests import requests
HAS_REQUESTS = True HAS_REQUESTS = True
except ImportError: except ImportError:
REQUESTS_IMP_ERR = traceback.format_exc()
HAS_REQUESTS = False HAS_REQUESTS = False
from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.basic import AnsibleModule, missing_required_lib
from ansible.module_utils.six.moves.urllib import parse as urllib_parse from ansible.module_utils.six.moves.urllib import parse as urllib_parse
from ansible.module_utils.rabbitmq import rabbitmq_argument_spec from ansible.module_utils.rabbitmq import rabbitmq_argument_spec
@ -132,7 +135,7 @@ def main():
) )
if not HAS_REQUESTS: if not HAS_REQUESTS:
module.fail_json(msg="requests library is required for this module. To install, use `pip install requests`") module.fail_json(msg=missing_required_lib("requests"), exception=REQUESTS_IMP_ERR)
result = dict(changed=False, name=module.params['name']) result = dict(changed=False, name=module.params['name'])

@ -142,13 +142,15 @@ import time
import traceback import traceback
from distutils.version import LooseVersion from distutils.version import LooseVersion
REQUESTS_IMP_ERR = None
try: try:
import requests import requests
HAS_REQUESTS = True HAS_REQUESTS = True
except ImportError: except ImportError:
REQUESTS_IMP_ERR = traceback.format_exc()
HAS_REQUESTS = False HAS_REQUESTS = False
from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.basic import AnsibleModule, missing_required_lib
from ansible.module_utils.six import PY3 from ansible.module_utils.six import PY3
from ansible.module_utils._text import to_native from ansible.module_utils._text import to_native
@ -156,7 +158,7 @@ from ansible.module_utils._text import to_native
def check_requests_dep(module): def check_requests_dep(module):
"""Check if an adequate requests version is available""" """Check if an adequate requests version is available"""
if not HAS_REQUESTS: if not HAS_REQUESTS:
module.fail_json(msg='requests is required for this module') module.fail_json(msg=missing_required_lib('requests'), exception=REQUESTS_IMP_ERR)
else: else:
required_version = '2.0.0' if PY3 else '1.0.0' required_version = '2.0.0' if PY3 else '1.0.0'
if LooseVersion(requests.__version__) < LooseVersion(required_version): if LooseVersion(requests.__version__) < LooseVersion(required_version):

@ -93,13 +93,15 @@ import platform
import traceback import traceback
# Import Datadog # Import Datadog
DATADOG_IMP_ERR = None
try: try:
from datadog import initialize, api from datadog import initialize, api
HAS_DATADOG = True HAS_DATADOG = True
except Exception: except Exception:
DATADOG_IMP_ERR = traceback.format_exc()
HAS_DATADOG = False HAS_DATADOG = False
from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.basic import AnsibleModule, missing_required_lib
from ansible.module_utils._text import to_native from ansible.module_utils._text import to_native
@ -127,7 +129,7 @@ def main():
# Prepare Datadog # Prepare Datadog
if not HAS_DATADOG: if not HAS_DATADOG:
module.fail_json(msg='datadogpy required for this module') module.fail_json(msg=missing_required_lib('datadogpy'), exception=DATADOG_IMP_ERR)
options = { options = {
'api_key': module.params['api_key'], 'api_key': module.params['api_key'],

@ -141,13 +141,15 @@ EXAMPLES = '''
import traceback import traceback
# Import Datadog # Import Datadog
DATADOG_IMP_ERR = None
try: try:
from datadog import initialize, api from datadog import initialize, api
HAS_DATADOG = True HAS_DATADOG = True
except Exception: except Exception:
DATADOG_IMP_ERR = traceback.format_exc()
HAS_DATADOG = False HAS_DATADOG = False
from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.basic import AnsibleModule, missing_required_lib
from ansible.module_utils._text import to_native from ansible.module_utils._text import to_native
@ -180,7 +182,7 @@ def main():
# Prepare Datadog # Prepare Datadog
if not HAS_DATADOG: if not HAS_DATADOG:
module.fail_json(msg='datadogpy required for this module') module.fail_json(msg=missing_required_lib('datadogpy'), exception=DATADOG_IMP_ERR)
options = { options = {
'api_key': module.params['api_key'], 'api_key': module.params['api_key'],

@ -68,13 +68,17 @@ EXAMPLES = '''
state: running state: running
''' '''
import traceback
PINGDOM_IMP_ERR = None
try: try:
import pingdom import pingdom
HAS_PINGDOM = True HAS_PINGDOM = True
except Exception: except Exception:
PINGDOM_IMP_ERR = traceback.format_exc()
HAS_PINGDOM = False HAS_PINGDOM = False
from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.basic import AnsibleModule, missing_required_lib
def pause(checkid, uid, passwd, key): def pause(checkid, uid, passwd, key):
@ -114,7 +118,7 @@ def main():
) )
if not HAS_PINGDOM: if not HAS_PINGDOM:
module.fail_json(msg="Missing required pingdom module (check docs)") module.fail_json(msg=missing_required_lib("pingdom"), exception=PINGDOM_IMP_ERR)
checkid = module.params['checkid'] checkid = module.params['checkid']
state = module.params['state'] state = module.params['state']

@ -214,18 +214,20 @@ import select
import socket import socket
import sys import sys
import time import time
import traceback
from ansible.module_utils.basic import AnsibleModule, load_platform_subclass from ansible.module_utils.basic import AnsibleModule, load_platform_subclass, missing_required_lib
from ansible.module_utils._text import to_native from ansible.module_utils._text import to_native
HAS_PSUTIL = False HAS_PSUTIL = False
PSUTIL_IMP_ERR = None
try: try:
import psutil import psutil
HAS_PSUTIL = True HAS_PSUTIL = True
# just because we can import it on Linux doesn't mean we will use it # just because we can import it on Linux doesn't mean we will use it
except ImportError: except ImportError:
pass PSUTIL_IMP_ERR = traceback.format_exc()
class TCPConnectionInfo(object): class TCPConnectionInfo(object):
@ -261,7 +263,7 @@ class TCPConnectionInfo(object):
self.port = int(self.module.params['port']) self.port = int(self.module.params['port'])
self.exclude_ips = self._get_exclude_ips() self.exclude_ips = self._get_exclude_ips()
if not HAS_PSUTIL: if not HAS_PSUTIL:
module.fail_json(msg="psutil module required for wait_for") module.fail_json(msg=missing_required_lib('psutil'), exception=PSUTIL_IMP_ERR)
def _get_exclude_ips(self): def _get_exclude_ips(self):
exclude_hosts = self.module.params['exclude_hosts'] exclude_hosts = self.module.params['exclude_hosts']

@ -31,7 +31,8 @@
assert: assert:
that: that:
- k8s_append_hash is failed - k8s_append_hash is failed
- "k8s_append_hash.msg == 'openshift >= 0.7.2 is required for append_hash'" - "'Failed to import the required Python library (openshift >= 0.7.2)' in k8s_append_hash.msg"
- "'. This is required for append_hash.' in k8s_append_hash.msg"
# merge_type # merge_type
- include_role: - include_role:

Loading…
Cancel
Save