YAML templates with available

I need to create a configuration file that itself has the YAML format. What is good practice?

The final file is as follows:

development: adapter: mysql2 database: tracks # set this if you are storing utf8 in your mysql database to handle strings # like "RÊnÊ". Not needed for sqlite. For PostgreSQL use encoding: unicode # encoding: utf8 host: localhost username: root password: qwerty 

Most of these variables must be defined, and some not by default. And this is YAML both in Wars and in the template. Therefore, I have to repeat almost the same structure at least twice: in the template and in the vars file.

The real problem is with optional parameters. To set the correct encoding (or none), I have to write something like:

 # tasks/configure.yml - include: {tracks_database}.yml # variables/mysql2.yml tracks_database_encoding: utf8 # templates/site.yml development: database: "{{ tracks_database }}" {% if tracks_database_use_utf8 %} encoding: "{{ tracks_database_encoding }}" {% endif %} 
  • It looks pretty ugly and breaks YAML formatting.
  • Lots of repetitive code

So, I looked at another way: save the configuration as it is in the variable, and simply write it to the configuration through the jijna filter .

 # group_vars/tracks.yml tracks_database_settings: development: name: tracks adapter: mysql2 host: localhost encoding: utf8 username: root password: qwerty # templates/site.yml {{ tracks_database_settings | to_nice_yaml }} 

But there are negative effects:

  • Comments lost
  • If I need to redefine only a few variables, I need to copy the whole structure. ( hash_behaviour=merge not an option).
  • It is not possible to preset variables for different types of db and include .
  • Dictionary items are reordered (sorted).

Is there a better way to template YAML files? An ideal solution would be something like:

 {{ tracks_database_default_settings_with_comments | with overriden values from group_vars/host_vars/whatever | with preset values from db-specific file | to_nice_yaml_with_comments }} 

I am currently looking at combining hashes / dictionaries , but I still don't know how / where to define combined dictionaries.


UPD: now I managed to do this:

 {{ tracks_database_defaults | combine(tracks_database_override, recursive=True) | to_nice_yaml }} 

But this looks unusual for the truth. And still uncomfortable.

+5
source share
1 answer

According to the current versioning behavior and your requirements:

  • hash_behaviour = merge is not an option
  • do not repeat yourself inside var and template files

You have chosen the best option.

Also note that combine (..., recursive = true) filter and hash_behaviour = merge use the same merge_hash .
This way, it will simply replace nested scalars or arrays.

+1
source

All Articles