I am trying to run a virtual environment in Ansible.
It is constantly erroring out.
Here's the code:
- name: Install virtualenv
pip: name=virtualenv
when: virtualenvexists.stat.exists != true
- name: Create virtualenv
sudo: true
command: virtualenv /home/vagrant/db/venv
- name: Activate
sudo: yes
sudo_user: vagrant
command: /home/vagrant/db/venv/bin/source /home/vagrant/db/venv/bin/activate
I get the error message:
{"cmd": "/home/vagrant/db/venv/bin/activate", "failed": true, "rc": 13} msg: [Errno 13] Permission denied
I've tried running this command as multiple users, and I'm also trying to figure out how to automatically run commands from the virtual instance without activating it, and I'm having no luck.
How do I run commands inside a virtual environment in Ansible?
I've also tried this with no luck:
- name: ansible_python_interpreter
set_fact:
ansible_python_interpreter: /home/vagrant/db/venv/bin/python
There are a number of problems here. The first is that you are creating the virtual environment as root
:
- name: Create virtualenv
sudo: true
command: virtualenv /home/vagrant/db/venv
But you are trying to access it as the vagrant
user:
- name: Activate
sudo: yes
sudo_user: vagrant
command: /home/vagrant/db/venv/bin/source /home/vagrant/db/venv/bin/activate
It is likely that you want sudo_user: vagrant
on both tasks.
Secondly, the source
command is a shell builtin, you won't find it at /home/vagrant/db/venv/bin/source
. So that command simply doesn't make sense.
Lastly, even if it did make sense, it would have no practical effect: That would modify the environment of the command
module, but would have no impact on subsequent tasks. There are a few ways of dealing with that; if you are simply trying to run a command that has been installed in your virtual environment you can run that directly:
command: /home/vagrant/db/venv/bin/somecommand
That will correctly use the version of Python installed in your virtual environment. Alternatively, you can embed everything into a shell script:
shell:
cmd: |
source /home/vagrant/db/venv/bin/activate
do_stuff_here
Update
For those "it doesn't work!" commenters, I present to you...a running example!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With