I’m writing a custom filter plugin in Python, to perform some complicated business logic which uses several values which are already known as Ansible variables. This is going to take a filename and return a list of modified versions of that filename, in a specific order, which will then be used with the ansible.builtin.first_found filter.
Is there a way for the Python code to access Ansible variables directly, rather than having to pass parameters to the filter function? These will include playbook_dir, role_path, a few calculated values, and a few “facts” supplied by /etc/ansible/facts.d/ files on the target machines.
I ask because the immediate problem I’m trying to solve needs the values of eight different variables, and I really don’t want to have to pass every single one of those variables to the filter every time I call it.
Filters aren’t really intended to access data they weren’t explicitly passed. While it might technically be possible, it’s easier to use a lookup plugin (which has a Templar instance available to it) for this purpose. A couple of toy examples can be found at 0_test.yml · GitHub and 0_test.yml · GitHub, or you can look at the usage of templating in the ansible.builtin.first_found and ansible.builtin.vars lookups.
The term “Templar” is not something I’ve ever seen in the context of computers, let alone Ansible.
Again, what is a “Templar instance”?
Your comment above mentioned it in passing, as if I’m supposed to already know what that means. I just asked for clarification - the email notification came in over the weekend, I plan on looking over those examples later today.
I did see it “in action”, I was asking where to find the official documentation about it. The search engines keep directing me to pages about a Nicholas Cage movie, or to the old religious order mentioned in that movie. It’s really weird, like … maybe the movie industry is paying google to send clicks their way or something?
Anyway. After a good night’s sleep, and reading the documentation about “lookup plugins”, it turns out that within the run() function I can use variables.get( 'xxx' , '' ) to retrieve the value of any variable that can be “seen” by the task which executes the plugin. This, plus “use a lookup plugin instead of a filter plugin”, are all I was looking for in the first place.
The only other thing I ran into is that environment happens to be an undocumented “magic” variable that you can’t use … but that’s not on anybody here, unless you’re part of the ansible documentation team.
Thanks for nudging me in the right direction, much appreciated.