Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

ansible

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/

like image 718
Matt Schlobohm Avatar asked Dec 13 '13 20:12

Matt Schlobohm


1 Answers

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 $@
like image 89
Matt Schlobohm Avatar answered Oct 05 '22 05:10

Matt Schlobohm