user12430166
user12430166

Reputation:

Preserve single quotes with to_nice_yaml()

When I try to pipe my variable array through to_nice_yaml then the usual way of preserving single quotes (wrapping them in double quotes) produces multiple single quotes.

test_playbook.yml

- hosts: all
  vars:
    some_test_param:
    - "'testy'"
  tasks:
  - name: Do stuff
    template:
      src: ~/test_template.j2
      dest: /home/remote_user/test_config.yml
      owner: remote_user
      group: remote_user
      mode: '600'
      lstrip_blocks: yes

test_template.j2

Test array goes here:
{{ some_test_param | to_nice_yaml }}

I expected the output to be

Test array goes here
- 'testy'

But instead it was

Test array goes here
- '''testy'''

Is there any way to fix this?

Upvotes: 1

Views: 2061

Answers (1)

Tahvok
Tahvok

Reputation: 56

Unless a string starts with a special character yaml does not need to quote strings.

This is also how to_nice_yaml works. To demonstrated, I have made a slight adjustment to your playbook:

- hosts: localhost
  vars:
    some_test_param:
      - "true"
  tasks:
  - name: Do stuff
    debug:
      msg: "{{ some_test_param | to_nice_yaml }}"

Clearly here I expect "true" to be a string and not a boolean, and this is exactly what to_nice_yaml produces:

ok: [localhost] => {
    "msg": "- 'true'\n"
}

Notice that 'true' is single quoted. Notice how it transforms my double quotes to single quotes - that is because it reads my variable as yaml, and then outputs it in its own way. And if I were to remove the quotes - as if I do need a boolean, the output would not be quoted:

- hosts: localhost
  vars:
    some_test_param:
      - true
  tasks:
  - name: Do stuff
    debug:
      msg: "{{ some_test_param | to_nice_yaml }}"

Outputs:

ok: [localhost] => {
    "msg": "- true\n"
}

I found a nice article on when to quote or not a string in yaml: http://blogs.perl.org/users/tinita/2018/03/strings-in-yaml---to-quote-or-not-to-quote.html

So when you're creating a string with a quote as "'testy'", it produces exactly that in the output, just with a single quote: '''testy''', this is the way for yaml to preserve a single quote inside single quotes.

tl;dr to_nice_yaml produces exactly what it says - reads your variable as yaml and outputs it in a correct yaml format.

If you need to add quotes to your string, you would have to do it with an additional task, such as replace or regex_replace filter.

Upvotes: 1

Related Questions