# running a command that requires a virtualenv

**URL:** <https://forum.ansible.com/t/running-a-command-that-requires-a-virtualenv/15184>\
**Category:** Ansible Project\
**Created:** [May 7, 2014, 1:59pm UTC](https://forum.ansible.com/t/running-a-command-that-requires-a-virtualenv/15184 "2014-05-07T13:59:52Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![david.neudorfer](https://avatars.discourse-cdn.com/v4/letter/d/b38774/32.png) [@david.neudorfer](https://forum.ansible.com/u/david.neudorfer)\
**Post date:** [May 7, 2014, 1:59pm UTC](https://forum.ansible.com/t/running-a-command-that-requires-a-virtualenv/15184/1 "2014-05-07T13:59:52Z")

</div>

Is this answer still considered the best way to run a command that requires a virtualenv to run?

[http://stackoverflow.com/questions/20040141/ansible-command-from-inside-virtualenv?rq=1](http://stackoverflow.com/questions/20040141/ansible-command-from-inside-virtualenv?rq=1)

pasting the answer for posterity,

```auto
---
# 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:

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

```
