来自virtualenv的Ansible命令?

mik*_*vis 37 virtualenv ansible

这看起来应该很简单:

tasks:
- name: install python packages
  pip: name=${item} virtualenv=~/buildbot-env
  with_items: [ buildbot ]
- name: create buildbot master
  command: buildbot create-master ~/buildbot creates=~/buildbot/buildbot.tac
Run Code Online (Sandbox Code Playgroud)

但是,除非首先获取virtualenv的激活脚本,否则该命令将不会成功,并且似乎没有在Ansible命令模块中执行此操作.

我已尝试在各种.profile,.bashrc,.bash_login等中获取激活脚本,但没有运气.或者,有shell命令,但它看起来像一个尴尬的黑客:

- name: create buildbot master
  shell: source ~/buildbot-env/bin/activate && \
         buildbot create-master ~/buildbot \
         creates=~/buildbot/buildbot.tac executable=/bin/bash
Run Code Online (Sandbox Code Playgroud)

有没有更好的办法?

mik*_*vis 25

这是包装器方法的通用版本.

venv_exec.j2:

#!/bin/bash
source {{ venv }}/bin/activate
$@
Run Code Online (Sandbox Code Playgroud)

然后是剧本:

tasks:
  - pip: name={{ item }} virtualenv={{ venv }}
    with_items:
      - buildbot
  - template: src=venv_exec.j2 dest={{ venv }}/exec mode=755
  - command: "{{ venv }}/exec buildbot create-master {{ buildbot_master }}"
Run Code Online (Sandbox Code Playgroud)


ana*_*nik 25

更好的方法是使用已安装脚本的完整路径 - 它将自动在其virtualenv中运行:

tasks:
- name: install python packages
  pip: name={{ item }} virtualenv={{ venv }}
  with_items: [ buildbot ]
- name: create buildbot master
  command: "{{ venv }}/bin/buildbot create-master ~/buildbot
            creates=~/buildbot/buildbot.tac"
Run Code Online (Sandbox Code Playgroud)

  • 值得注意的是,任何人在摸不着头的时候磕磕绊绊,虽然在它的完整路径_usually_工作时调用可执行文件,但它并不完全相同:https://github.com/pypa/pipenv/issues/393#issue- 233266934 (2认同)

Mat*_*ohm 8

这是一种为整个游戏启用virtualenv的方法; 这个例子在一个游戏中构建virtualenv,然后在下一个游戏中开始使用它.

不确定它有多干净,但它确实有效.我只是建立一下mikepurvis在这里提到的内容.

---
# Build virtualenv
- hosts: all
vars:
  PROJECT_HOME: "/tmp/my_test_home"
  ansible_python_interpreter: "/usr/local/bin/python"
tasks:
  - name: "Create virtualenv"
    shell: virtualenv "{{ PROJECT_HOME }}/venv"
           creates="{{ PROJECT_HOME }}/venv/bin/activate"

  - name: "Copy virtualenv wrapper file"
    synchronize: src=pyvenv
                 dest="{{ PROJECT_HOME }}/venv/bin/pyvenv"

# Use virtualenv
- hosts: all
vars:
  PROJECT_HOME: "/tmp/my_test_home"
  ansible_python_interpreter: "/tmp/my_test_home/venv/bin/pyvenv"
tasks:
  - name: "Guard code, so we are more certain we are in a virtualenv"
    shell: echo $VIRTUAL_ENV
    register: command_result
    failed_when: command_result.stdout == ""
Run Code Online (Sandbox Code Playgroud)

pyenv包装文件:

#!/bin/bash
source "$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )/activate"
python $@
Run Code Online (Sandbox Code Playgroud)