问题
I have developed a custom ansible module that has a dependency on a 3rd party library PyYAML. However running the playbook yields
ansible_module_my_module.py, line 5, in <module>
import yaml
ImportError: No module named yaml
I see PyYAML in the ansible requirements.txt (https://github.com/ansible/ansible/blob/stable-2.8/requirements.txt) so I know its installed/used on the host machine. I'm wondering if there is a recommended way to install it on the remote machine?
I can add a step in the playbook using the pip ansible module to install it on the remote. Something like
- hosts: all
tasks:
- name: Installing PyYAML python library using Ansible pip module
pip:
name: PyYAML
But that means the playbook knows implementation details about modules buried deep down the stack which seems wrong. My expectation is that there is some way to tell ansible to install the 3rd party libraries on the remote machine as part of its setup. For example adding a requirements.txt in my module and ansible appends it to its setup, but I can't seem to find an elegant way to do it. Any help is appreciated.
回答1:
First ansible detecting dependencies and automatically installing it is against their philosophy of installing as little as possible on hosts. To get around that I ended up wrapping my custom module in a role and passing variables to that role instead of directly to the module. So users set role variables and call it using include_role
and tasks_from
after including it in their requirements.yml. Then I used the pip module (https://docs.ansible.com/ansible/latest/modules/pip_module.html) to setup the environment as a task in the role before the task that calls my custom module.
The second issue I faced was that ansible will default to the /usr/bin/python
even when executed via a virtualenv. This is, apparently designed behavior. To get around that I had to include ansible_python_interpreter
to manually set it to the virtualenv when running locally.
来源:https://stackoverflow.com/questions/56536334/correct-way-to-setup-the-environment-when-developing-custom-ansible-modules-that