Accessing variable data from a filter

Hello!

I might be going around the problem in the wrong way, but I seem to need to access the variable cache from a filter plugin.

I am trying to create a map filter, that can be used like so:

  • name: Test Play
    hosts: 127.0.0.1
    connection: local
    vars:
    input:
  • foo
  • bar
    data:
    foo: 4
    bar: 5
    baz: 6
    tasks:
  • debug: msg=“{{ input | map(”{{data[in]}}“) }}”

I am expecting it to print [4,5].

It seems that the way to solve it was to include a jinja expression as the parameter to the filter which will be evaluated for each element of the list, by substituting their value in place of the in symbol, which I took the liberty to hard-code.

Unfortunately for this to work I need to be able to access the variable cache within the filter:

from ansible.utils import template

def _map(arg, expr):
vars = {}
return map(lambda x: template.template_from_string(None, expr, dict(vars, in = x), True), list(arg))

class FilterModule(object):

‘’’ Ansible extra jinja2 filters ‘’’

def filters(self):
return {
‘map’: _map,
}

This results in an error:

fatal: [127.0.0.1] => One or more undefined variables: ‘data’ is undefined

I have been browsing through the code for 3 hours, but could not find a way to get a copy of all variables, similar to task.py: https://github.com/ansible/ansible/blob/devel/lib/ansible/playbook/task.py#L225,L230

Can anyone lend a hand?

Thanks,
Akos Vandra

first of all, 'map' is an existing jinja2 filter, also currently
filters have no way to access the variable cache, they only deal with
data passed to them.

I know map is an existing jinja2 filter, but as far as I see they are capable of calling “methods” only on the elements themselves, and they are not able to be used as I would intend to.

But, please, correct me if i’m wrong.

Akos