4

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?

Community
  • 1
  • 1
Russ Huguley
  • 766
  • 3
  • 9
  • 13
  • 1
    Possible duplicate of [In YAML, how do I break a string over multiple lines?](https://stackoverflow.com/questions/3790454/in-yaml-how-do-i-break-a-string-over-multiple-lines) – Hamish Downer Sep 19 '17 at 15:17

2 Answers2

10

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.

udondan
  • 57,263
  • 20
  • 190
  • 175
5

Maybe what you need is the | literal?

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

This will not 'fold' newlines into spaces, as oposed to >

Yu Hao
  • 119,891
  • 44
  • 235
  • 294
franmr
  • 51
  • 1
  • 3