Arno Schots
Arno Schots

Reputation: 45

Multiline variable in Ansible playbook without newlines (spaces)

I am trying to define a "complex" (with quotes) multiline variable in Ansible. I don't want spaces as a result of the multiline setup. A "newline" at the end of each line is translated into a space. I have tried escaping the newline with "" as indicated in many questions/answers on the internet, but Ansible seems to ignore the "".

Code example:

      set_fact: 
        test: >-
          "v=DKIM1; k=rsa;" "p=MIIBIjANBgkqhkwetuwweeTYRjEFAAOCAQ8AMIIBCgKCA\
          QEAtJltC/t70wayxq0Rws5R7t+Q2GZ2llnY0nSHDkVnP9kDaYBTyHCk+OoiCehHjUr\
          9/60Rp7v5xDiS9ta5w8c4pyqgWCIvj7iCPVfVzEtSfOp0iwmvGvKeBMhY62+7BYyQ5\
          zOt45pJHVqQt78/L2S75AZY2RUVv85AXXUlx8Os54dBz8DsdnWilH+o0Ce+ZAor70i\
          z0TkEVCnuom" "3xv/bLbOyFI7EoxbhU2NVIer3uanPbl6HUr4B2P3y695yh4fi+oq\
          oOAM8Ah0rx0iruqcgoEPhNriEJ1PxW6ZDwFFnDgmR3hCaULQl4OtkWGwhG87ISBxC3\
          66xBjT+rTLys1yT0uu3QIDAQAB""

This leads to spaces everywhere there is a newline (at the end of the lines). E.g.:

"v=DKIM1; k=rsa;" "p=MIIBIjANBgkqhkwetuwweeTYRjEFAAOCAQ8AMIIBCgKCA (space!!!) QEAtJltC/t70wayxq0Rws5R7t+Q2GZ2llnY0nSHDkVnP9kDaYBTyHCk+OoiCehHjUr...

How can this be fixed?

Upvotes: 3

Views: 18095

Answers (2)

Vladimir Botka
Vladimir Botka

Reputation: 68254

Use folded style and split the lines. Then join them. For example, given the simplified data

    test: |-
       "v=DKIM1; k=rsa;" "p=MIIB
       QEAtJltC/t70wayxq0Rws5R7"

The debug task

    - debug:
        msg: "{{ test|split('\n')|join }}"

gives

  msg: '"v=DKIM1; k=rsa;" "p=MIIBQEAtJltC/t70wayxq0Rws5R7"'

For Ansible less than 2.11 use split as a method

    - debug:
        msg: "{{ test.split('\n')|join }}"

Upvotes: 4

Kevin C
Kevin C

Reputation: 5760

Try this:

set_fact:
  test: 'a\
    b\
    c'

If you use a variable, you can use:

set_fact:
  my_var: abc

set_fact:
  test: >-
    {{ my_var -}}
    def
    {{- my_var }}

That will result in 'abcdefabc'.

Upvotes: 0

Related Questions