Skip to main content

Problem

Recently I was working on a playbook to set up Apache basic HTTP authentication with the Ansible htpasswd module, and because the Python passlib module wasn't installed on the server I was getting an Ansible error:

"msg": "This module requires the passlib Python library"

Solution

I don't have root access to the server and could only install passlib in a Python virtual environment.  The problem then moved to Ansible—how to make Ansible use the virtual environment interpreter for the htpasswd task?

The Ansible variable controlling the Python interpreter is ansible_python_interpreter.  I didn't find a way to directly set this variable for a specific task. What I did find is the environment parameter for tasks.  However, there's no environment variable to directly specify ansible_python_interpreter.

It is possible, though, to tell Ansible to use the python that is specified by the environment.

With that glue in place, the next step is to specify the $PATH value for the specific task:

- name: Add users to .htpasswd file.
  htpasswd:
    path: path_to_htpasswd_file
    name: user_name
    password: password
    mode: 0644
  # Use previously-installed python virtual env executable so that passlib is available.
  # This requires that ansible_python_interpreter = "/usr/bin/env python"
  environment:
    PATH: '{{ ansible_env.HOME }}/path_to_python_virtual_env/bin:{{ ansible_env.PATH }}'

 

Comments

Ed Perkins

Jan 28, 2023 - 6:09am

Thanks for this elegant solution 👍

Add new comment