Accessing variable data from a filter

207 views
Skip to first unread message

Akos Vandra

unread,
Jan 1, 2015, 2:59:23 PM1/1/15
to ansible-project
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

Brian Coca

unread,
Jan 2, 2015, 1:41:16 PM1/2/15
to ansible...@googlegroups.com
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.

--
Brian Coca

Akos Vandra

unread,
Jan 3, 2015, 10:37:55 AM1/3/15
to ansible-project
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


--
Brian Coca

--
You received this message because you are subscribed to the Google Groups "Ansible Project" group.
To unsubscribe from this group and stop receiving emails from it, send an email to ansible-proje...@googlegroups.com.
To post to this group, send email to ansible...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/ansible-project/CAJ5XC8nroXX6eA2Aw-4a9WUTgqvqh6JqAEWxENkS-Poy-yq6XA%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.

Reply all
Reply to author
Forward
0 new messages