'jinja to json in Salt

I have a jinja template in salt that every time apply.state is ran, salt thinks it has changed when it hasn't.

The issue is that a reconfigure command executes when the file "changes", and this reconfigure would change the file from a single lined JSON to a lined JSON. For example:

salt creates the file like:

{ "key1": { "sub-key1": "sub-value1", "sub-key2": "sub-value2"}, "key2": "value2" }

but when the reconfigure command executes, it changes the file to:

{
  "key1": {
    "sub-key1": "sub-value1",
    "sub-key2": "sub-value2"
  },
  "key2": "value2"
}

Is there a way to have salt create the file as a formatted JSON to begin with?

This is what I have:

{{ gb_server.secrets_file }}:
  file.managed:
    - source: {{ gb_server.secrets_tmpl }}
    - user: {{ gb_server.secure_user }}
    - group: {{ gb_server.secure_user }}
    - mode: 600
    - template: jinja

the template is as follow:

{%- import_yaml 'gb-server/defaults.yaml' as defaultmap -%}
{%- set  secrets = gb_server_config['secrets'] -%}
{{ secrets|tojson|replace('\\\\n','\\n') }}

The values are in pillar in yaml format.

Ideally, the resulted JSON would have its key sorted alphabetically, that way the content of the resulted file wouldn't "change" and the reconfigure command wouldn't run every single time.

Is there a way to make this happen with salt?

Thank you.



Solution 1:[1]

It looks like file.serialize will do what you want here

{{ gb_server.secrets_file }}:
  file.serialize:
    - user: {{ gb_server.secure_user }}
    - group: {{ gb_server.secure_user }}
    - mode: 600
    - data: {{ gb_server.secrets }}
    - serializer: json
    - serializer_opts:
      - indent: 2
      - sort_keys: true

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 OrangeDog