Best way to always run ansible inside a virtualenv on remote machines?

Is there a better way to run ansible inside a virtualenv on the remote machines?

So far the way I can see is to modify the .bashrc file, manually or with ansible itself.

For example:

 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: Check if the ways it could be done using ssh authorized keys: http://binblog.info/2008/10/20/openssh-going-flexible-with-forced-commands/


Here's a way to enable the virtualenv for an entire play; this example builds the virtualenv in one play, then starts using it the next.

Not sure how clean it is, but it works. I'm just building a bit on what mikepurvis mentioned here.

---
# 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 wrapper file:

#!/bin/bash
source "$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )/activate"
python $@
链接地址: http://www.djcxy.com/p/17916.html

上一篇: 配置PhpStorm以使用.htaccess

下一篇: 在远程机器上总是运行virtualenv的最佳方式?