[Question] Jinja2 template - check variable

Hi,

is it possible in Jinja2 template to define possible values for some variable.

Let say I have template config1.j2:

parameter1={{var1 | default(1) }}
parameter2={{var2 | default(2) }}
parameter3={{var3 | default(3) }}

So, I would like that to parameter1…3 must be assigned only values 1 or 2 or 3.
How to achieve that without using “if” statement.

Is it possible somehow to define possible values like is “default” value is defined?

Hi,

There is no such filter for that but you can do that with if. IMHO jinja template is not right place for validating variable values. Much better place would be playbook.

How would you do that in playbook…
My playbook has only a few lines, all logic is done in templates.
I have maybe 300 variables per environment, if I all that do in playbook, then playbook would be pretty unreadable.

This is done in the template, I check is var in some list (list contain possible values). But, how to raise an exception if the variable is not in the list of possible (acceptable) values.

Dana utorak, 21. veljače 2017. u 14:29:01 UTC+1, korisnik Adam Hamsik napisao je:

Hi,

Not able to raise an error would be one of reasons to not do it in template. Can you share more about your setup that could help.

Adam, thank you…

I made ansible role for deploying specific configuration for application system which is developed by my company.

Configuration consists of 20 configuration files per environment.
For every of that configuration file I wrote jinja2 template.
Variables are defined in inventory file (combination of single variables, lists and dictionaries ).

So, I would like to avoid human made mistakes (tip fillers etc) with variable checking in templates.
In the playbook, I chose which config file(template) should be deployed to the certain environment (not all files are deployed to every environment, ie. to env1 I deploy 13 config files, to env2 16config files and to env3 all).

Since there is a lot of variables and various types of variables(single, lists and dict) it would be praticulary impossible to check variable in playbook.

Dana utorak, 21. veljače 2017. u 16:08:25 UTC+1, korisnik Adam Hamsik napisao je:

Hi,

I think you have some options but I’m not sure if they are usable for you

  1. use validate option for each template this would need script/binary which can verify if generated document is correct or not.

  2. Implement own filter which could be used to verify you input data

  • you need to have a filter per variable
  1. Simple data verification can be done this way

https://gist.github.com/haad/b005de9bd6e7fef2d8b744de55473eab#file-verification-input-yaml

  1. I have also done variable validation with json schema it looked like this

https://gist.github.com/haad/b005de9bd6e7fef2d8b744de55473eab#file-json-schema-validation-yaml