Creating a virtualenv as another user

I’m wanting to create a new account, then create a virtualenv beneath said account. Assuming my new user is created, and is called ‘cbweb’, I was trying to do something like this:

  • name: set up web app virtualenv
    pip: name=flask virtualenv=/home/cbweb/.virtualenvs/here_be_virtualenv
    user: cbweb
    sudo: True

I get an error when I try to run this:

$ vagrant provision
[dev] Running provisioner: ansible…
ERROR: multiple actions specified in task set up web app virtualenv
Ansible failed to complete successfully. Any error output should be
visible above. Please fix these errors and try again.

I am assuming that the user/sudo flags aren’t available for this ‘pip’ module. If this is true, what’s the best way to idempotently create a virtualenv as another user? I guess I could use the “command” module with the “creates” param, but wanted to see if there was a better way to make this work.

Apologies if there is an obvious answer to this, my Googling turned up a bunch of unrelated stuff.

User is not a task tag as its the user mgmt module. You want sudo_user

Brian Coca

Thanks, I’m still a bit confused as to when to use one or the other. I changed this and everything appears to have worked well.

Something I did notice is that using a variable in place of a string value for sudo_user seems to result in a syntax error:

  • name: set up web app virtualenv
    pip: name=flask virtualenv=/home/cbweb/.virtualenvs/here_be_virtualenv
    sudo: True
    sudo_user: {{ unprivved_app_user }}

$ vagrant provision
[dev] Running provisioner: ansible…
ERROR: Syntax Error while loading YAML script, /Users/gtaylor/Documents/workspace/vagrant/pathwright/provisioning/roles/python_host/tasks/main.yml
Note: The error may actually appear before this position: line 54, column 15

sudo: True
sudo_user: {{ unprivved_app_user }}
^
Ansible failed to complete successfully. Any error output should be
visible above. Please fix these errors and try again.

The variable is populated and works in other tasks in this same file, but always seems to die due to a syntax error in this case. Any ideas?

You been to quote {{ if they are first thing after :.

Brian Coca

Thanks. I tried using a dollar sign instead of braces, and that seemed to work as well. Is it more “correct” to use the quoted braces or the dollar sign variable in this case?

both are correct, but ${} is deprecated and might be dropped in the future.

thing: { key: value } is shorthand for a hash/dictionary in yaml, that is
why the jinja substitution needs to be escaped
thing : "{{ var }}" or yaml will think you have an incomplete hash, but not
needed when part of a module

thing: name={{var}} as yaml will not think of it as a hash but as part of
the value name=...

Thanks for that explanation, I’m not extremely familiar with YAML.