Ansible pyenv virtualenv 给出 pip 错误?

Nil*_*esh 5 python pip ansible pyenv

我有 ansible 任务

- name: Install setuptools in virtual environment
  pip:
      name: setuptools-git
      virtualenv: "myenv"
      virtualenv_command: "/root/.pyenv/bin/pyenv virtualenv 2.7.13"
Run Code Online (Sandbox Code Playgroud)

但它给出了错误

fatal: [localhost]: FAILED! => {
    "changed": false,
    "invocation": {
        "module_args": {
            "chdir": null,
            "editable": false,
            "executable": null,
            "extra_args": "",
            "name": [
                "setuptools-git"
            ],
            "requirements": null,
            "state": "present",
            "umask": null,
            "use_mirrors": true,
            "version": null,
            "virtualenv": "myenv",
            "virtualenv_command": "/root/.pyenv/bin/pyenv virtualenv 2.7.13",
            "virtualenv_python": null,
            "virtualenv_site_packages": false
        }
    },
    "msg": "Unable to find pip in the virtualenv, myenv, under any of these names: pip2, pip. Make sure pip is present in the virtualenv."
}
Run Code Online (Sandbox Code Playgroud)

当我检查 virtualenv 中的 pip 文件时,它已经存在

# ls -alh /root/.pyenv/versions/myenv/bin/pip
-rwxr-xr-x 1 root root 243 Jan 16 17:40 /root/.pyenv/versions/myenv/bin/pip
Run Code Online (Sandbox Code Playgroud)

有 2 个同名的 virtualenv

# /root/.pyenv/bin/pyenv virtualenvs
2.7.13/envs/myenv (created from /root/.pyenv/versions/2.7.13)
myenv (created from /root/.pyenv/versions/2.7.13)
Run Code Online (Sandbox Code Playgroud)

executable我不能与变量一起使用virtualenv

And*_*rew 2

我找到了一种解决方法,可以使用 pip 将软件包安装到由 pyenv 管理的 virtualenv 中。它确实避免使用 pip 模块,而只是执行一些 shell 命令。我提供了一些我使用的变量、我创建的.pyenvrc文件以及执行 shell 魔法的 ansible 任务。

变量

# Installation paths
pyenv_root: "{{ ansible_env.HOME }}/.pyenv"
pyenv_rc: "{{ pyenv_root }}/.pyenvrc"
# Whatever your virtualenv is named
pyenv_venv_name: "foo_virtualenv"
project_dir: /path/to/your/project
Run Code Online (Sandbox Code Playgroud)

任务

- name: Pip - install requirements using shell
  shell: |
    # cd to project directory
    cd {{ project_dir }}
    # Check to see if we are already inside a virtualenv
    if ! [[ ${VIRTUAL_ENV} ]]; then
        # Load pyenv into the shell
        source {{ pyenv_rc }}
        # Activate the virtualenv
        pyenv activate {{ pyenv_venv_name }}
    fi
    # Install python requirements 
    pip install -r requirements.txt
  args:
    executable: /bin/bash
  register: pip_script_result
Run Code Online (Sandbox Code Playgroud)

.pyenvrc的内容:

# Installation paths
pyenv_root: "{{ ansible_env.HOME }}/.pyenv"
pyenv_rc: "{{ pyenv_root }}/.pyenvrc"
# Whatever your virtualenv is named
pyenv_venv_name: "foo_virtualenv"
project_dir: /path/to/your/project
Run Code Online (Sandbox Code Playgroud)

在上面的示例中,我将requests.txt的内容安装pip到我的 pyenv 管理的 virtualenv 中。您应该能够调整生产pip install线来完成您需要的任何操作。