79142207

Date: 2024-10-30 17:36:30
Score: 1
Natty:
Report link

So after a couple of months, leaving this issue to the side, I finally found a useful (at least for myself) solution.

next to the filter_plugins directory, I create the module_utils directory. In here, I put everything I want to import from a filter:

├── roles
│   └── my_role
│       └── tasks
│       └── filter_plugins
│       └── module_utils
│           └── my_python_module
│       └── ...

Now, in if there is anything I need to import, I use the following piece of code:

#!/usr/bin/python

import sys

class FilterModule(object):

    def filters(self):
        return {
            "my_filter": self.my_filter
        }

    def my_filter(self, argument):
        current_file = __file__
        current_path = os.path.dirname(current_file)
        parent_path = os.path.dirname(current_path)
        module_path = parent_path+"/module_utils"

        sys.path.append(module_path)
        import my_python_module

You can treat the module_utils directory just like the lib/python3.x/site-packages directory. So if you install packages via pip, you can copy them from lib/python3.x/site-packages to your module_utils directory.

For instance, I created a fresh venv, activated it and ran the following command:

pip3 install jdcal openpyxl

This installed the following files in my ~/venv/lib/python3.9/site-packages:

$ ls -ln ~/venv/lib/python3.9/site-packages
...
drwxr-xr-x 1 4096 4096     0 30 okt 18:09 et_xmlfile
drwxr-xr-x 1 4096 4096     0 30 okt 18:09 et_xmlfile-2.0.0.dist-info
-rw-r--r-- 1 4096 4096 12462 30 okt 18:10 jdcal.py
drwxr-xr-x 1 4096 4096     0 30 okt 18:10 jdcal-1.4.1.dist-info
drwxr-xr-x 1 4096 4096     0 30 okt 18:09 openpyxl
drwxr-xr-x 1 4096 4096     0 30 okt 18:09 openpyxl-3.1.5.dist-info
...

Next, I copied the directories et_xmlfile and openpyxl and the file jdcal.py to the module_utils directory of my role and used the above piece of code to succesfully import the openpyxl module in my filter.

Reasons:
  • Blacklisted phrase (0.5): I need
  • RegEx Blacklisted phrase (1): I want
  • Long answer (-1):
  • Has code block (-0.5):
  • Self-answer (0.5):
  • Low reputation (0.5):
Posted by: Johan G