5
我需要模板configuration file,它本身具有YAML格式。什么是一个好的做法呢?Templating YAML with ansible
最终的文件看起来是这样的:
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
大多数这些变量应该定义和一些需要非缺省值。这是YAML无论是在变量和模板。所以我必须重复几乎相同的结构至少两次:在模板和变量文件中。
真正的问题是可选参数。要设置正确的编码(或无)我有写类似:
# 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 %}
- 这看起来相当丑陋,打破了YAML格式。
- 大量的重复的代码
所以,我认为是另一种方式:存储配置,因为它是一个变量,只是把它写在配置through a 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 }}
但也有负面影响:
- 评论丢失
- 如果我需要重写刚才几个变量,我必须复制整个结构。 (
hash_behaviour=merge
不是一个选项)。 - 无法为不同的db类型预置变量,
include
它们。 - 字典中的元素得到重新安排(排序)。
有没有更好的方式模板化YAML文件?完美的解决办法是这样的:
{{ 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 }}
我目前看combining hashes/dictionaries,但我仍然不知道如何/在哪里定义合并字典。
UPD:现在我成功地做到这一点:
{{ tracks_database_defaults | combine(tracks_database_override, recursive=True) | to_nice_yaml }}
但它看起来非常不寻常的ansible。仍然不方便。