20

I'm attempting to install psycopg2 into a Python virtualenv with Ansible's pip module, but I need to prepend an entry to PATH for it to build correctly (it needs to know the path to the directory containing pg_config). I see that I can pass environment to the pip module, but I'm unsure of how to prepend rather than overwrite PATH.

Here I'm attempting to prepend the path with the necessary directory, but it overwrites the virtualenv PATH and fails:

- pip:
    name: psycopg2
    virtualenv: /path/to/my/venv
  environment:
    PATH: /usr/pgsql-9.3/bin:$PATH
Collin Allen
  • 574
  • 1
  • 7
  • 16

1 Answers1

36

If you are using Ansible 1.4 or later (which I recommend) you can access the remote PATH env variable:

- pip: name=psycopg2 virtualenv=/path/to/my/venv
  environment:
    PATH: /usr/pgsql-9.3/bin:{{ ansible_env.PATH }}

If instead you are interested in the PATH env var of the local client running the Ansible scripts (instead of the targeted server), then you want to do the following:

- pip: name=psycopg2 virtualenv=/path/to/my/venv
  environment:
    # This only makes sense if your client and server are homogeneous, that is,
    # they have the same PATHs.
    PATH: /usr/pgsql-9.3/bin:{{ lookup('env', 'PATH') }}
Lekensteyn
  • 6,111
  • 6
  • 37
  • 55
Rico
  • 2,185
  • 18
  • 19
  • 4
    The `ansible_env.PATH` option was what I needed — worked perfectly. Thanks! – Collin Allen Feb 21 '14 at 04:56
  • 1
    Note that this takes the PATH of the workstation, not the server! – vdboor Mar 12 '14 at 08:38
  • 4
    If you need to prepend `~/bin`, use `PATH: "{{ansible_env.HOME}}/bin:{{ansible_env.PATH}}"`. If you instead use `PATH: "~/bin:{{ansible_env.PATH}}"`, then some programs (such as Python's `shutil.which`) are unable to use that component. – Lekensteyn Sep 18 '14 at 17:29
  • 3
    Be also aware that `ansible_env` refers to the environment of the SSH user, not the `sudo` environment. `ansible_env.USER` may therefore result in `root` rather than an unprivileged user. – Lekensteyn Sep 18 '14 at 17:30