I am currently developing a number of Ansible modules using Python. My directory structure looks like this:
/
playbook.yml
library/
module1.py
module2.py
Using this, I can run the playbook (which uses my modules) via
ansible-playbook playbook.yml
Now I want to add a code file shared between my modules.
So I added the file library/shared.py
and added the line
from shared import my_shared_func
to all of my modules, so that I can call my_shared_func()
in all modules.
The problem is, that when calling ansible-playbook
again, this causes the error message
ModuleNotFoundError: No module named 'shared'
I am assuming, that Ansible is not copying the shared file to the execution host.
Can my problem be solved, or do all Ansible modules have to be completely self contained in a single file?
The solution is described in the "Using and developing module utilities" documentation:
To reduce the maintenance burden in a collection or in local modules, you can extract duplicated code into one or more module utilities and import them into your modules. For example, if you have your own custom modules that import a my_shared_code library, you can place that into a ./module_utils/my_shared_code.py file like this:
from ansible.module_utils.my_shared_code import MySharedCodeClient
When you run ansible-playbook, Ansible will merge any files in your local module_utils directories into the ansible.module_utils namespace in the order defined by the Ansible search path.
So, place you shared.py
in module_utils/shared.py
, and then in your module import it like:
from ansible.module_utils.shared import my_shared_func