Quick Tip: Making Ansible Execute Python Within a Virtualenv or Non Standard Path on Targets

Mon Feb 06, 2017 · 165 words

One of the interesting things in Ansible-land is that all of the (non-Windows) modules in the upstream contain a very specific shebang, in particular #!/usr/bin/python.

As a result I’ve seen a few bad patterns in the wild:

  1. Symlinking the desired Python executable to /usr/bin/python

  2. Manually installing Python on that path

  3. Giving up and use the raw module

Good news, you don’t need to do any of that. Within group_vars/host_vars or inside of your INI-style inventory you can simply do something like:


ansible_python_interpreter=’/usr/bin/env python’

Or in the case of inventory vars:

# group_vars/all
ansible_python_interpreter: /usr/bin/env python

# host_vars/web-node-1
ansible_python_interpreter: /usr/my/custom/path/python-2.6

Notice how this implies (and correctly so!) that you can specify different python interpreter paths for different segments of you inventory.

Pro-Tip: You can also leverage this patten whenever you dynamically add hosts via the add_host module. This would looks something like:

# someplaybook_or_taskfile.yml

- name: Add new hosts to in-memory inventory
      host: "{{ some_dynamic_var }}"
      groups: bitcoin_workers
      ansible_python_interpreter: /my/python/installed/here



Back · About · Blog · Projects · Contact · Home