总是在远程机器上的virtualenv中运行ansible的最佳方法?

时间:2013-12-13 20:08:10

标签: ansible

有没有更好的方法在远程机器上的virtualenv中运行ansible?

到目前为止,我看到的方法是手动修改.bashrc文件或使用ansible本身。

例如:

 tasks:
    - name: "Enable virtualenv in .bashrc"
      lineinfile: dest=.bashrc
                  line="source {{ PROJECT_HOME }}/venv/bin/activate"

    #
    # Put tasks that rely on this precondition here (?)
    #

    # Optionally, disable this later on
    - name: "Disable virtualenv in .bashrc"
      lineinfile: dest=.bashrc
                  line="source {{ PROJECT_HOME }}/venv/bin/activate"
                  state=absent

TODO:检查是否可以使用ssh授权密钥完成:http://binblog.info/2008/10/20/openssh-going-flexible-with-forced-commands/

1 个答案:

答案 0 :(得分:4)

这是一种为整个游戏启用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 == ""

pyenv包装文件:

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