Prevent ansible from re-ordering JSON?

Hey,

I’ve this weird situation when I’m passing json(as a string) it still reordering it’s order and not consistent.

Example:

my_var: |
  {
    "b": 1
    "a": 2
  }

when running ansible with
`

  • name: “Set up json file”
    copy:
    dest: “/tmp/file.json”
    content: “{{ my_var }}”

`

every ansible run the file is being changed(because json order is being changed), in order to fix it I’m using:
content: "{{ my_var | from_json | to_nice_json }}"

This command keeps the order the same each run, because to_nice_json sorts the output (sort_keys=True).

My question is why my_var is being changed all the time even it’s a string and not json

This is something Ansible is inherited from Python, dictionary in Python is unordered.

Thanks.

Hey Kai,

The thing is that is not a dictionary but string, pay attention to the “|” after my_var:

my_var: |
  {
    "b": 1
    "a": 2
  }

To 'keep it a string' content: "{{ my_var|string }}" , from_json
actually forces conversion (which would be happening anyways)