Ansible / python错误:没有名为ansible.errors的模块

时间:2019-01-04 01:07:08

标签: ansible ansible-2.x

我已经作为RHEL的root用户使用“ pip”安装了Ansible

python版本-Python 2.7.5

Ansible版本-

ansible 2.7.4
  config file = None
  configured module search path = [u'/root/.ansible/plugins/modules', u'/usr/share/ansible/plugins/modules']
  ansible python module location = /usr/lib/python2.7/site-packages/ansible
  executable location = /bin/ansible
  python version = 2.7.5 (default, May 31 2018, 09:41:32) [GCC 4.8.5 20150623 (Red Hat 4.8.5-28)]

每当我尝试将ansible用作另一个获得错误的用户

错误:

$ ansible --version
Traceback (most recent call last):
  File "/usr/bin/ansible", line 40, in <module>
    from ansible.errors import AnsibleError, AnsibleOptionsError, AnsibleParserError
ImportError: No module named ansible.errors

我发现两个位于不同位置的ansible文件,这是异常现象吗? 一个位于/ bin / ansible,另一个位于/ usr / bin / ansible

$ cd /bin
$ ls -lart ansible
-rwxr-xr-x 1 root root 5837 Dec  9 13:12 ansible
$ cd ansible
-ksh: cd: ansible: [Not a directory]
$ ls -lart /usr/bin/ansible
-rwxr-xr-x 1 root root 5837 Dec  9 13:12 /usr/bin/ansible

/ bin / ansible的内容

$ cat /bin/ansible
#!/bin/python

# (c) 2012, Michael DeHaan <michael.dehaan@gmail.com>
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Ansible.  If not, see <http://www.gnu.org/licenses/>.

########################################################
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type

__requires__ = ['ansible']
try:
    import pkg_resources
except Exception:
    # Use pkg_resources to find the correct versions of libraries and set
    # sys.path appropriately when there are multiversion installs.  But we
    # have code that better expresses the errors in the places where the code
    # is actually used (the deps are optional for many code paths) so we don't
    # want to fail here.
    pass

import os
import shutil
import sys
import traceback

from ansible.errors import AnsibleError, AnsibleOptionsError, AnsibleParserError
from ansible.module_utils._text import to_text


# Used for determining if the system is running a new enough python version
# and should only restrict on our documented minimum versions
_PY3_MIN = sys.version_info[:2] >= (3, 5)
_PY2_MIN = (2, 6) <= sys.version_info[:2] < (3,)
_PY_MIN = _PY3_MIN or _PY2_MIN
if not _PY_MIN:
    raise SystemExit('ERROR: Ansible requires a minimum of Python2 version 2.6 or Python3 version 3.5. Current version: %s' % ''.join(sys.version.splitlines()))


class LastResort(object):
    # OUTPUT OF LAST RESORT
    def display(self, msg, log_only=None):
        print(msg, file=sys.stderr)

    def error(self, msg, wrap_text=None):
        print(msg, file=sys.stderr)


if __name__ == '__main__':

    display = LastResort()

    try:  # bad ANSIBLE_CONFIG or config options can force ugly stacktrace
        import ansible.constants as C
        from ansible.utils.display import Display
    except AnsibleOptionsError as e:
        display.error(to_text(e), wrap_text=False)
        sys.exit(5)

    cli = None
    me = os.path.basename(sys.argv[0])

    try:
        display = Display()
        display.debug("starting run")

        sub = None
        target = me.split('-')
        if target[-1][0].isdigit():
            # Remove any version or python version info as downstreams
            # sometimes add that
            target = target[:-1]

        if len(target) > 1:
            sub = target[1]
            myclass = "%sCLI" % sub.capitalize()
        elif target[0] == 'ansible':
            sub = 'adhoc'
            myclass = 'AdHocCLI'
        else:
            raise AnsibleError("Unknown Ansible alias: %s" % me)

        try:
            mycli = getattr(__import__("ansible.cli.%s" % sub, fromlist=[myclass]), myclass)
        except ImportError as e:
            # ImportError members have changed in py3
            if 'msg' in dir(e):
                msg = e.msg
            else:
                msg = e.message
            if msg.endswith(' %s' % sub):
                raise AnsibleError("Ansible sub-program not implemented: %s" % me)
            else:
                raise

        try:
            args = [to_text(a, errors='surrogate_or_strict') for a in sys.argv]
        except UnicodeError:
            display.error('Command line args are not in utf-8, unable to continue.  Ansible currently only understands utf-8')
            display.display(u"The full traceback was:\n\n%s" % to_text(traceback.format_exc()))
            exit_code = 6
        else:
            cli = mycli(args)
            cli.parse()
            exit_code = cli.run()

    except AnsibleOptionsError as e:
        cli.parser.print_help()
        display.error(to_text(e), wrap_text=False)
        exit_code = 5
    except AnsibleParserError as e:
        display.error(to_text(e), wrap_text=False)
        exit_code = 4
# TQM takes care of these, but leaving comment to reserve the exit codes
#    except AnsibleHostUnreachable as e:
#        display.error(str(e))
#        exit_code = 3
#    except AnsibleHostFailed as e:
#        display.error(str(e))
#        exit_code = 2
    except AnsibleError as e:
        display.error(to_text(e), wrap_text=False)
        exit_code = 1
    except KeyboardInterrupt:
        display.error("User interrupted execution")
        exit_code = 99
    except Exception as e:
        if C.DEFAULT_DEBUG:
            # Show raw stacktraces in debug mode, It also allow pdb to
            # enter post mortem mode.
            raise
        have_cli_options = cli is not None and cli.options is not None
        display.error("Unexpected Exception, this is probably a bug: %s" % to_text(e), wrap_text=False)
        if not have_cli_options or have_cli_options and cli.options.verbosity > 2:
            log_only = False
            if hasattr(e, 'orig_exc'):
                display.vvv('\nexception type: %s' % to_text(type(e.orig_exc)))
                why = to_text(e.orig_exc)
                if to_text(e) != why:
                    display.vvv('\noriginal msg: %s' % why)
        else:
            display.display("to see the full traceback, use -vvv")
            log_only = True
        display.display(u"the full traceback was:\n\n%s" % to_text(traceback.format_exc()), log_only=log_only)
        exit_code = 250
    finally:
        # Remove ansible tmpdir
        shutil.rmtree(C.DEFAULT_LOCAL_TMP, True)

    sys.exit(exit_code)

列表:

$ ls -lart /usr/lib/python2.7/site-packages/ansible/errors/
total 36
-rw-------  1 root root  3820 Dec  9 13:12 yaml_strings.py
-rw-------  1 root root 11555 Dec  9 13:12 __init__.py
-rw-------  1 root root  3147 Dec  9 13:12 yaml_strings.pyc
-rw-------  1 root root 11535 Dec  9 13:12 __init__.pyc
drwx------  2 root root    88 Dec  9 13:12 .
drwx------ 17 root root  4096 Dec  9 13:12 ..

任何人都可以帮助我解决它。

3 个答案:

答案 0 :(得分:1)

这是因为安装无法使/usr/lib/python2.7/site-packages/ansible中的文件被组或世界读取,这意味着只有文件所有者(在这种情况下为root)才能读取它们:

$ ls -lart /usr/lib/python2.7/site-packages/ansible/errors/
total 36
-rw-------  1 root root 11555 Dec  9 13:12 __init__.py
#   ^^^^^^ should be -rw-r--r-- for files

您可以使用chmod来更改此特定问题,但将来可能会希望先运行umask go-w,以使pip的权限默认为0600对于它写出的文件

# chmod -R a+rX /usr/lib/python2.7/site-packages/ansible

该表达式中的X用来设置eXecute位,但仅用于已在用户权限下执行的文件(因此,用于目录和可执行文件,而不用于“普通”文件;您可以阅读man 1 chmod中的完整故事)

答案 1 :(得分:0)

就我而言,我在python中使用venv工作,这导致Ansible找不到所有的python模块。在这里不一定是OP的问题,但值得意识到。

答案 2 :(得分:0)

就我而言,问题如下:

我正在使用 sudo 执行命令,与我在 ssh 服务器中发布的公钥相比,它选择了不同的 .ssh/id_rsa.pub。这理所当然地导致权限被拒绝。

这只是通过执行发现的(取自使用 -vvv 的 ansible ping 命令的转储。请注意,我已将 -v 命令添加到 ssh,它为您提供有关登录过程中失败的提示。< /p>

sudo sshpass -d11 ssh -v -C -o ControlMaster=auto -o ControlPersist=60s -o 'User="ubuntu"' -o ConnectTimeout=10 -o ControlPath=/root/.ansible/cp/66b206be85 10.115.216.134 '/bin/sh -c '"'"'echo ~ubuntu && sleep 0'"'"''