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

Ansible/python错误:没有名为Ansible.errors的模块,ansible,ansible-2.x,Ansible,Ansible 2.x,我已经在RHEL上使用“pip”作为根用户安装了Ansible python版本-python 2.7.5 可翻译版本- 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/p

我已经在RHEL上使用“pip”作为根用户安装了Ansible

python版本-python 2.7.5

可翻译版本-

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
/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
$ 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)

有人能帮我解决吗

这是因为安装没有使
/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
用于设置执行位,但仅适用于已在用户权限中执行的文件(因此,适用于目录和可执行文件,但不适用于“普通”文件;您可以在中阅读全文)

在我的例子中,我在python的venv中工作,这导致Ansible找不到它的所有python模块。可能不一定是OP的问题,但值得注意。

在我的案例中,问题是:

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

只有通过使用-vvv执行(取自ansible ping命令的转储)才能发现这一点。请注意,我已将-v命令添加到ssh中,这将提示您在登录过程中失败了什么

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'"'"''

根据
可执行文件位置=/bin/ansible
文件/usr/bin/ansible,您似乎安装了两个ansible副本
;事实上,ansible有两个副本吗?不确定为什么找到了两个文件。这是否异常?我已在上面进行了更新。这有点异常,但根据该输出,它们可能是硬链接,或者(我想更可能)那
/usr/bin
/bin
的一个符号链接,所以我不认为这是问题所在。只是为了好玩,你能不能包括
cat/bin/ansible
的输出,还有
ls-l/usr/lib/python2.7/site包/ansible/errors
包括cat/bin/ansible和ls-l/usr/lib/python2.7/site-pac的输出@matthewldaniel上面的kages/ansible/errors在应用
chmod
$ansible回溯(最近一次调用):文件“/usr/bin/ansible”,第67行,导入ansible.constants作为C文件“/usr/lib/python2.7/site packages/ansible/constants.py”,第11行,来自jinja2导入模板ImportError:在这种情况下,没有名为jinja2的模块,只运行相同的
chmod
,但针对所有
站点包
;该目录中的所有内容都不应该敏感,很抱歉,我没有想到第一次就这么说——我想,特别是隧道视觉,如果你有我们已经设置了一个Anaconda环境以使用bash激活,为了使用Ansible命令,您必须使用
conda deactivate
来停用它。这就是我的案例@Zenul_Abidin。谢谢!
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'"'"''