I’m referring a question into here after opening an issue on github. I’ll copy my question from the issue:
Say I’m writing a new module, and I want to have an argument which points to a file (which I’d like to read or whatever). I want it to be possible to receive an absolute path or a “relative” one (pointing to roles/x/files directory).
How can I receive such a “relative” path and resolve it to the actual file? I couldn’t find a way to do that.
Moreover, I tried to run the “test-module” script on the “copy” core module (as if it was just a custom module), and it wasn’t able to resolve a relative path.
Meaning, as far as I understand it, there’s nothing special in the “copy” module’s code, but it is being invoked in a different way (and so does all the core modules).
Ansible modules run on the target server, so they don't have access to the controlling machine's files at all. If you need to access local files you need an action plugin. That's where the actual magic of the copy module happens
Hagai
PS switched jobs I see?
Well, that’s a little too many undocumented magic :\
According to you suggestion, I tried to write my own custom action plugin; I placed it under playbook-dir/action_plugins/my_mod_name.py.
Here’s the code:
`
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)
`
Then, in the module, the “myarg” argument will have the file content (not the path).
I hope this is the right way to do it.
PS in a way
I don’t really remember how it’s done, but action plugins can transfer files to a temp dir on the remote machine, which your module can then use. The copy action plugin does that iirc.