j. davila

Quick Tip, Making Ansible Execute Python Within a virtualenv or Non Standard Path on Targets

Estimated Reading Time: 1 minute

One of the interesting things in the Ansible ecosystem 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:

INI Style

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 pattern 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: ""
groups: bitcoin_workers
ansible_python_interpreter: /my/python/installed/here