Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

A prettier way to handle spaces with enters in YAML

This is more of a styling question. I have this ugly piece of code:

- name: download something
  shell: "wget https://www.{{ my_var }}\
    a_string\
    {{ a_very_long_string_to_show_what_i_mean }}"

In my opinion, this looks very ugly. Since the URL must be a ‘whole’, without spaces and quoting and whatnot, I need to escape each newline with a \. Yuck.

However, I can’t use breaks, e.g. > or | since that will include spaces in the end result, and the code will error.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Following the ansible-lint guidelines, I do not want the string size on a single line to be larger than something about 84 characters. In this example, when I have to download a file, I can’t simply put on a single line.

Expected output:

- name: pretty download something
  shell:
    wget https://www.{{ my_var }}
    a_string
    {{ a_very_long_string_to_show_what_i_mean }}

>Solution :

However, I can’t use breaks, e.g. > or | since that will include spaces in the end result, and the code will error.

That is actually only an half true statement.
You can combine it with the whitespace control mechanism of Jinja to remove those unneeded whitespaces.

Basically, adding a dash to the opening or the closing of an expression blocks do trim the extraneous whitespace or carriage return before or after it.


Given:

- hosts: localhost
  gather_facts: no

  tasks:
    - debug:
        msg: >-
          wget https://www.{{ my_var -}}
          a_string
          {{- a_very_long_string_to_show_what_I_mean -}}
      vars:
        my_var: example.org/
        a_very_long_string_to_show_what_I_mean: _foo

This yields:

ok: [localhost] => 
  msg: wget https://www.example.org/a_string_foo

Note that in:

wget https://www.{{ my_var -}}

The dash on the opening moustache is not needed, because there is no extra space before that variable.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading