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。仍然不方便。