Is there a way to used dot-nested vars with 'default' filter in jinja2 templates?

748 views
Skip to first unread message

Kesten Broughton

unread,
Apr 24, 2014, 10:06:13 AM4/24/14
to ansible...@googlegroups.com

I have the need to template a yaml file using vars in another yaml file as input.  There are often defaults.

I'd like to do this

in vars.yml
parentvar:
  childvar:
    subvar1: val1
#  subvar2 is not even listed to keep user vars.yml file concise

template.yml
{{ parentvar.childvar.subvar1 }}
{{ parentvar.childvar.subvar2 | default("default for subvar2") }}

This fails with "dict object has no attribute 'subvar2'

It would work fine if i had
vars.yml
parentvar_childvar_subvar1: val1
 
and template.yml
{{ parentvar_childvar_subvar1 }}
{{ parentvar_childvar_subvar2 | default("default for subvar2") }}

I presume this is a problem at the jinja2 level? 

I would like to avoid the '_' flattened solution as it becomes pretty unreadable for large config files.
Any suggestions on how to work around this?

thanks

Kesten Broughton
512 701 4209

C. Morgan Hamill

unread,
Apr 24, 2014, 10:25:11 AM4/24/14
to ansible-project
Not positive if this will work, but try:

Excerpts from Kesten Broughton's message of 2014-04-24 10:06:13 -0400:
> template.yml
> {{ parentvar.childvar.subvar1 }}
> {{ parentvar.childvar.get('subvar2', 'default for subvar2') }}
--
Morgan Hamill

Matt Martz

unread,
Apr 24, 2014, 10:33:54 AM4/24/14
to ansible...@googlegroups.com
It works best to use standard hash key access such as:

foo['bar']['baz']|default('qux')

Jinja2 seems to be able to handle it better.
--
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/CAO2fFsVRHaaqdZrJ2idE_JUR2HDOkcbuxP%3DjqkDUecBda%3DsbRA%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.


--
Matt Martz
ma...@sivel.net
http://sivel.net/
Reply all
Reply to author
Forward
0 new messages