2016-04-29 54 views
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。仍然不方便。

回答

1

根据当前变量的管理行为和你的要求:

  • hash_behaviour =合并是不是一种选择
  • 不要重复自己内部var和模板文件

你选择了最好的选项。

另外,请注意,combine(..., recursive=True)过滤器和hash_behaviour=merge使用相同的merge_hash函数。
因此,它将简单地替换嵌套标量或数组。