pythonansibleansible-module

Ansible Custom Module in Python - How to resolve relative role file paths?


I'm writing a new Ansible Custom Module in Python.

I want to be able to resolve paths in my code (in order to read their content) just as file and copy modules do when receiving a relative path in src argument (the path is relative to root-dir/roles/x/files), for instance.

Is it possible to do so? And if so, how?

As this seems to be impossible at the moment, I've added a feature request here.


Solution

  • I've posted this question on "ansible-devel" group, and they gave me a direction which led me to an answer.

    You can write a custom action plugin and place it under root-playbook-dir/action_plugins. The file name must be "your_mod_name.py"

    The code would be something like this:

    #!/usr/bin/python
    
    from ansible.runner.lookup_plugins.file import LookupModule as FilePlugin
    from ansible import utils
    
    class ActionModule(object):
    
        def __init__(self, runner):
            self.runner = runner
    
        def run(self, conn, tmp_path, module_name, module_args, inject, complex_args=None, **kwargs):
    
            options = {}
            options.update(utils.parse_kv(module_args))
    
            file_plugin = FilePlugin()
            files_content = file_plugin.run(terms=options.get('myarg'), inject=inject)
            options['myarg'] = files_content[0]
    
            return self.runner._execute_module(conn=conn, tmp="/tmp", module_name="mymod", args=utils.serialize_args(options), inject=inject)
    

    The code uses the "file" lookup plugin to read the file, and then executes the custom module and returns its result.

    Eventually, your custom module will receive the file contents (not the path) in the "myarg" argument.