How to easily test/experiment with jinja templating in ansible?

I’ve been bitten one too many times by the way that ansible interacts with jinja. I’d say its error handling is a little bit too lax, defaulting to return empty strings or similar things that then end up getting my playbooks to fail later down the line.

To prevent that, I know that I can have a better look at the available vars and facts gathered with the setup module

ansible -m setup

but often I’d like to see how I can use these with jinja: I’d like to have a REPL for it (or failing that, a shorter feedback loop)

debug tasks inside a playbook are not ideal also because I cannot use them to debug issues with templates used before tasks execution (e.g. to define a variable)

I was thinking of simply using

ansible -m debug -a “msg={{the_jinja_expression_I_want_to_test}}”

but I realized that the output is not quite what I’d expect:

ansible -m debug -a “msg={{hostvars[inventory_hostname]}}”

for example returns

kalivm | success >> {
“msg”: “{‘ansible_ssh_host’:”
}

and

ansible -m debug -a “msg={{hostvars}}”

prints

kalivm | success >> {
“msg”: “{‘kalivm’:”
}

It seems to be a truncated json string, probably because not all the variables have yet been made available there in a simple ansible module invocation (they’d probably be available in a full playbook run)

Is this known behavior? How do you usually handle these things?

Thanks

I usually attach a debugger,
http://michaeldehaan.net/post/35403909347/tips-on-using-debuggers-with-ansible

or set a small template action to dump the contents of the dictionary/variable whatever to a local file on my box.
It’s easier to inspect it that way,

I agree it’s not totally obvious.

The answer at http://serverfault.com/a/695798 helped me figure out that it needed to be quoted.

quote your test expressions and you get the output you expected:

ansible --version

ansible 1.9.6
configured module search path = None

ansible -m debug -a msg=“‘{{hostvars[inventory_hostname]}}’”

localhost | success >> {
“msg”: “{‘inventory_hostname’: ‘127.0.0.1’, ‘group_names’: [‘ungrouped’], ‘inventory_hostname_short’: ‘127’}”
}

and 2 years later …
: )