ansibleyamlmultilineansible-lint

How to break a string over Literal Block Scalar in Ansible


I have a variable in YAML script like that:

variable: |
  This is really long long line ---------------------------------------------------------------------------
  And this line is not really long ---------
  And I am just chilling here

I want to validate all my scripts through YAMLLint, so I have to break the first line in two without changing its contents.
How can I achieve this?

If I try to define it literally, I am getting something like this:

variable: "\
  This is really long long line ---------------------\
  ------------------------------------------------------\n
  And this line is not really long ---------\n
  And I am just chilling here"

I am getting something like this (note the spaces in the second 2 lines):

  This is really long long line ---------------------------------------------------------------------------
   And this line is not really long ---------
   And I am just chilling here

And other options just doesn't work. How do I obey YAMLLint rules in this sutuation?


Solution

  • You are seeing this behaviour because you are explicitly adding newlines, and then, adding a carriage return for the rest of the text.

    You can go around this multiple ways:

    1. Add the carriage return before the explicit newline:
      variable: "\
        This is really long long line ---------------------\
        ------------------------------------------------------
        \nAnd this line is not really long ---------
        \nAnd I am just chilling here"
      
    2. Use a blank line to add a newline:
      variable: "\
        This is really long long line ---------------------\
        ------------------------------------------------------
      
        And this line is not really long ---------
      
        And I am just chilling here"
      
    3. Use a Jinja comment to control whitespaces:
      variable: |
        This is really long long line ---------------------{#- -#}
        ------------------------------------------------------
        And this line is not really long ---------
        And I am just chilling here
      

    All the above would give you the expected and would pass an ansible-lint test:

    This is really long long line ---------------------------------------------------------------------------
    And this line is not really long ---------
    And I am just chilling here