Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

yaml multi line syntax without newline to space conversion

Tags:

ansible

I have something like this dictionary:

env: qat
target_host: >
         {%if env in ['prd'] %}one
         {%elif env in ['qat','stg'] %}two
         {%else%}three
         {%endif%}

when I print it I get:

ok: [localhost] => { "var": { "target_host": "two " } }

So it is converting the \n at the end of the line to a space. Which is exactly what it is supposed to do. However in this case I am just trying to spread out the lines to make the structure of the if/else more readable and I don't want the extra space. It works as expected if I put it all on one line without the > but I would like to be able to make it multiline just so its easier to read.

I found this question Is there a way to represent a long string that doesnt have any whitespace on multiple lines in a YAML document?

So I could do:

env: qat
target_host: "{%if env in ['prd'] %}one\
              {%elif env in ['qat','stg'] %}two\
              {%else%}three\
              {%endif%}"

And that gives the desired result.

Is there anyway to accomplish this without cluttering it up even more?

like image 970
Russ Huguley Avatar asked Dec 06 '22 21:12

Russ Huguley


1 Answers

In Jinja* you can strip whitespaces/newlines by adding a minus sign to the start/end of a block. This should do the trick:

env: qat
target_host: >
         {%if env in ['prd'] -%}one
         {%- elif env in ['qat','stg'] -%}two
         {%- else -%}three
         {%- endif%}

* Jinja 2 is the templating engine used by Ansible.

like image 169
udondan Avatar answered Mar 06 '23 10:03

udondan