Transform multiline jinja2 block to single line

1.2k views Asked by At

I use ansible (which uses jinja2) to manage nginx. My nginx config file has a very long line which is hard to maintain:

add_header Content-Security-Policy "default-src 'self' http: https: https://*.foo.com: https://*.bar.com: https://*.baz.com: https://*.qux.com: https://*.spam.com: https://*.ham.com: https://*.eggs.com: wss://*.foo.com: object-src 'none'" always;

Since the config file is a jinja2 template, I want to rewrite that single line as multiple lines (for ease of maintenance), but for it to be transformed to one line as above.

How do I do that? In other words something like this (doesn't work of course):

add_header Content-Security-Policy {%
"default-src 'self'
http:
https:
https://*.foo.com:
https://*.bar.com:
https://*.baz.com:
https://*.qux.com:
https://*.spam.com:
https://*.ham.com:
https://*.eggs.com:
wss://*.foo.com:
object-src 'none'"
always;%}

...which when transformed, will give me the one liner shown above?

1

There are 1 answers

0
Zeitounator On BEST ANSWER

A possible solution: put your needed values in a list and join them with spaces:

{%- set my_values=[                                               
"default-src 'self'",                                             
"http:",                                                          
"https:",                                                         
"https://*.foo.com:",                                             
"https://*.bar.com:",                                             
"https://*.baz.com:",                                             
"https://*.qux.com:",                                             
"https://*.spam.com:",                                            
"https://*.ham.com:",                                             
"https://*.eggs.com:",                                            
"wss://*.foo.com:",                                               
"object-src 'none'",                                              
"always",                                                         
]-%}                                                              
add_header Content-Security-Policy "{{ my_values | join(' ') }}"; 

Cherry on the cake: pass this list directly to your template from a var you declare in your inventory/playbook.