I have a configuration file where a particular setting takes a long ugly json-style dictionary. I would like to define this dictionary in YAML and print it out with Jinja. Currently this looks something like this:
{%- load_yaml as some_conf_val %}
val1: something
val2: completely
val3: different
{%- endload %}
option = {{ some_conf_val }}
# Results in:
option = {'val2': 'completely', 'val1': 'something', 'val3': 'different'}
By happy coincidence this is exactly the format expected by the program being configured, and the yaml block is much easier to read and modify than the inline version. However, the fact that the keys come out in neither alphabetical order nor the order they were defined leads me to suspect their output order is non-deterministic. On re-running the state a few times they always come out in the same order, but that doesn't prove much.
This is a problem because if the output string is altered, it gets treated as a change to the file and triggers a service restart, even if nothing functional has been changed. I don't care what specific order the keys are in, but I do need that order to be the same every time.
How can I accomplish this? Or is it already deterministic and just doesn't look like it?
(If I understand correctly jinja dicts are really python dicts under the hood, and python dicts are unordered, so this may be impossible without including code that's messier than the line I'm trying to not have to write. But I'm hoping not.)
It turns out that saltstack provides a filter for json output that sorts its keys and can be massaged to get what I wanted. The solution I eventually used looks like this:
option = {{ some_conf_val|json|replace('"', "'") }}
# Results in:
option = {'val1': 'something', 'val2': 'completely', 'val3': 'different'}
The replace operation is because the option eventually gets fed to something that cares what kind of quotes it's looking at. It may not apply in other circumstances.
As far as I can tell the sorting behavior isn't documented, but you can find it in the source here.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments