4

I am trying to run a virtual environment in Ansible.

It is constantly erroring out.

Here's the code:

- name: Install virtualenv
  pip: name=virtualenv
  when: virtualenvexists.stat.exists != true

- name: Create virtualenv
  sudo: true
  command: virtualenv /home/vagrant/db/venv

- name: Activate
  sudo: yes
  sudo_user: vagrant
  command: /home/vagrant/db/venv/bin/source /home/vagrant/db/venv/bin/activate

I get the error message:

{"cmd": "/home/vagrant/db/venv/bin/activate", "failed": true, "rc": 13} msg: [Errno 13] Permission denied

I've tried running this command as multiple users, and I'm also trying to figure out how to automatically run commands from the virtual instance without activating it, and I'm having no luck.

How do I run commands inside a virtual environment in Ansible?

I've also tried this with no luck:

- name: ansible_python_interpreter
  set_fact:
    ansible_python_interpreter: /home/vagrant/db/venv/bin/python
4

2 回答 2

9

这里有很多问题。首先是您将虚拟环境创建为root

- name: Create virtualenv
  sudo: true
  command: virtualenv /home/vagrant/db/venv

但是您正试图以vagrant用户身份访问它:

- name: Activate
  sudo: yes
  sudo_user: vagrant
  command: /home/vagrant/db/venv/bin/source /home/vagrant/db/venv/bin/activate

您可能希望sudo_user: vagrant同时完成这两项任务。

其次,该source命令是一个内置的 shell,你不会在/home/vagrant/db/venv/bin/source. 所以这个命令根本没有意义。

最后,即使它确实有意义,它也没有实际效果:那会修改command模块的环境,但不会影响后续任务。有几种处理方法;如果您只是尝试运行已安装在虚拟环境中的命令,则可以直接运行:

command: /home/vagrant/db/venv/bin/somecommand

这将正确使用安装在您的虚拟环境中的 Python 版本。或者,您可以将所有内容嵌入到 shell 脚本中:

shell:
  cmd: |
    source /home/vagrant/db/venv/bin/activate
    do_stuff_here

更新

对于那些“它不起作用!” 评论者,我向你展示......一个运行的例子

于 2015-10-29T13:21:44.657 回答
0

~/.synapse以通过执行pip模块在位于的虚拟环境中安装突触的以下示例为例。

- pip:
    name: 'https://github.com/matrix-org/synapse/tarball/master'
    virtualenv: ~/.synapse
    virtualenv_site_packages: yes
    virtualenv_python: python2.7

然后,在新创建的虚拟环境中运行命令。使用chdir参数并确保在前面加上command:withbin/

- command: bin/python -m synapse.app.homeserver --server-name {{ matrix_hostname }}
--config-path homeserver.yaml --generate-config --report-stats=yes
  args:
    chdir: ~/.synapse
    creates: homeserver.yaml
于 2016-12-06T21:48:24.223 回答