Strange behavior in Ansible when using `to_nice_yaml` filter

Viewed 112

I have an ansible playbook, which first initializes a fact using set_fact, and then a task that consumes the fact and generates a YAML file from it.

The playbook looks like this

- name: Test yaml output
  hosts: localhost
  become: true
  tasks:
     - name: set config
       set_fact:
         config:
            A12345: '00000000000000000000000087895423'
            A12352: '00000000000000000000000087565857'
            A12353: '00000000000000000000000031200527'
     - name : gen yaml file
       copy:
           dest: "a.yaml"
           content: "{{ config | to_nice_yaml }}"

Actual Output

When I run the playbook, the output in a.yaml is

A12345: 00000000000000000000000087895423
A12352: 00000000000000000000000087565857
A12353: '00000000000000000000000031200527'

Notice only the last line has the value in quotes

Expected Output

The expected output is

A12345: '00000000000000000000000087895423'
A12352: '00000000000000000000000087565857'
A12353: '00000000000000000000000031200527'

All values should be quoted.

I cannot, for the life of me, figure out why only the last line has the value printed in single-quotes.

I've tried this with Ansible version 2.7.7, and version 2.11.12, both running against Python 3.7.3. The behavior is the same.

1 Answers

It's because 031200527 is an octal number, whereas 087895423 is not, thus, the octal scalar needs quoting but the other values do not because the leading zeros are interpreted in yaml exactly the same way 00hello would be -- just the ascii 0 followed by other ascii characters

If it really bothers you that much, and having quoted scalars is obligatory for some reason, to_nice_yaml accepts the same kwargs as does pyyaml.dump:

- debug:
    msg: '{{ thing | to_nice_yaml(default_style=quote) }}'
  vars:
    quote: "'"
    thing:
      A1234: '008123'
      A2345: '003123'

which in this case will also quote the keys, but unconditionally quotes the scalars

Related