kapitan icon indicating copy to clipboard operation
kapitan copied to clipboard

dynamically over-riding jinja2 Environment

Open starkers opened this issue 5 years ago • 4 comments

When templating something that already contains golang {{ }} in jinja2 the common practice is to liberally spread terrible raw and endraw blocks everywhere..

a classic example now is prometheus alertmanager rules...

EG:

{% raw %}
            description: Filesystem on {{ $labels.device }} at {{ $labels.instance }}
{% endraw %}

This is extremely painful... especially if u want to pull in the latest upstream ones... for example the current kube-prom has over 178 {{ references at the time of writing..

Obviously one can use jb to do the rules seperatelly from the bulk but this is just one usecase that is luckily vendored in jsonnet

A solution to this in ansible at least is to use some magic at the start of your file.. specifically.. over-ride the jinja2.Environment with alternative variable_start_string and variable_end_string's..

for example.. change it from {{ + }} to [% and %] :

$ head -3 ansible-alerts-rules.yaml.j2
#jinja2:variable_start_string:'[%' , variable_end_string:'%]', trim_blocks: False
# [% ansible_managed %]
# on behalf of: [% component %]

Those params seem to line up with https://jinja.palletsprojects.com/en/2.11.x/api/?highlight=environment#jinja2.Environment

This would ALSO be useful to allow users to adjust trim_blocks or whatever else they want to set

I've not had a moment to examine ansible's source but I would like to just open the topic up for debate in the hopes that someone more skilled at python than me feels inspired to make my life easier lol

starkers avatar Jun 23 '20 13:06 starkers

I think it would be good to also be able to set these options globally.

pvanderlinden avatar Jun 23 '20 17:06 pvanderlinden

I would expect a way to override jinja2 Environment options in the same place where input_type: jinja2 is written.

tavin avatar Mar 25 '24 12:03 tavin