jinja2 equivalent to python's "in" operator?

31,644 views
Skip to first unread message

Erik Johnson

unread,
Feb 7, 2012, 7:46:06 PM2/7/12
to salt-...@googlegroups.com
Consider the following scenario:

1) I have a number of config files to deploy. They all are named similarly, allowing for me to use templating to cut down on the amount of file states I have to type out.

2) Several of these config files also have a shell script that accompany them, with the same naming convention. But not every config file has a shell script, so I can't just put both file states within the same for loop.

I can just break it up into two separate for loops, with one loop having states for both config file and shell script, and another with the ones that just have shell scripts. However, this means that the code that sets up the file state for the config file is duplicated, which is something I would like to avoid. What I would really like is something like the following pseudo-code:

for type in 'a','b','c','d','e','f'

  config file state goes here
 
  if type not in 'd','f'
    shell script state goes here
  endif

endfor

This link (http://jinja.pocoo.org/docs/templates/#builtin-tests) would suggest there is no built-in test to see if a value is a member of a given iterable, but I was wondering if there was perhaps another way to tackle this.

Seth House

unread,
Feb 7, 2012, 8:20:35 PM2/7/12
to salt-...@googlegroups.com
It is in there. The Jinja docs are a little hard to navigate for some reason -- I often have a hard time finding what I'm looking for.


In addition you need to make your lists explicit Python lists. For example:

>>> from jinja2 import Template
>>> t = Template("""
... {%- for type in ('a','b','c','d','e','f') -%}
...  {%- if type not in ('d','f') -%}
...   {{ type }}
...  {%- endif -%}
... {%- endfor -%}""").render()
>>> print t
abce

Erik Johnson

unread,
Feb 8, 2012, 2:22:38 PM2/8/12
to salt-...@googlegroups.com
I'm having trouble getting this to work. Here's my sls: http://pastie.org/3343269

when I run state.show_highstate, I get the following:

{'hostname': ('Rendering SLS monit.beta failed, render error:\nmapping values are not allowed here\n  in "<unicode string>", line 3, column 7:\n      file:\n          ^',)}

Seth House

unread,
Feb 8, 2012, 2:56:58 PM2/8/12
to salt-...@googlegroups.com
There are missing colons after both ID decs:

http://pastie.org/3343340 (untested, sorry. busy afternoon)

Erik Johnson

unread,
Feb 8, 2012, 3:01:21 PM2/8/12
to salt-...@googlegroups.com
WTF... those were there before I changed the syntax, I swear... I know because I ran the highstate just fine before.

Thanks for pointing out my obvious mistake. :)
Reply all
Reply to author
Forward
0 new messages