2015-12-21 87 views
7

我们在salt管理的我们的爪牙上运行多个Python虚拟环境。SaltStack:来自SLS文件的数据的属性(计算值)?

系统的名称是此架构建设:

project_customer_stage 

例子:

supercms_favoritcustomer_p 

支柱数据:

systems: 
    - customer: favoritcustomer 
    project: supercms 
    stage: p 
    - customer: favoritcustomer 
    project: supercms 
    stage: q 

对于每一个virtualenv中,我们有一个Linux用户。到目前为止,我们计算像这样的“家”这样的值:

{% for system in pillar.systems %} 
    {% set system_name = system.project + '_' + system.customer + '_' + system.stage %} 
    {% set system_home = '/home/' + system_name %} 
    ... 

但它是多余的。

我们如何避免复制粘贴{% set system_home = ...%}

我喜欢的方式面向对象的编程工作:

  • 你可以定义一个属性的主目录
  • 如果您需要在特殊的情况下,不同的主目录,那么你可以继承基类并覆盖基类的工作方式。

在盐你有YAML和模板...这两个很好的东西。但在我的情况下,OOP会很好。

回答

3

您也可以动态生成支柱数据。看看下面的例子为柱子的文件:从systems.yml文件

{% import_yaml "systems.yml" as systems %} 

systems: 
{% for system in systems %} 
{% set name = system['name'] | default(system.project + '_' + system.customer + '_' + system.stage) %} 
{% set home = system['home'] | default('/home/' + name) %} 
    - name: {{ name }} 
    customer: {{ system['customer'] }} 
    project: {{ system['project'] }} 
    stage: {{ system['stage'] }} 
    home: {{ home }} 
{% endfor %} 

这一支柱定义负载YAML数据,其中盐会看着你的pillar_root目录。该文件可能是这样的(非常类似于您最初的例子):

- customer: smith 
    project: cms 
    stage: p 
- customer: jones 
    project: shop 
    stage: p 
    name: jones_webshop_p # <-- alternate name here! 

注意,这个例子计算,如项目名称和用户的主目录属性动态,除非它们在你的数据文件中明确定义。为此,Jinja default() filter用于支柱定义。

使用这个支柱定义,你可以简单地在你的状态定义使用namehome直接从支柱数据:

{% for system in salt['pillar.get']('systems') %} 
{{ system.home }}: 
    file.directory 
{% endfor %} 

此外,因为在我看来,这些神社重SLS文件有点难以阅读,你可以考虑切换到你的支柱文件Python renderer

#!py 

import yaml 

def run(): 
    systems = [] 
    with open('systems.yml', 'r') as f: 
    data = yaml.safe_load(f) 

    for system in data: 
     if not 'name' in system: 
     system['name'] = "%s_%s_%s" % (system['project'], system['customer'], system['stage']) 

     if not 'home' in system: 
     system['home'] = "/home/%s" % name 

     systems.append(system) 

    return {"systems": systems} 
+0

我同意你的看法:“这些Jinja重的SLS文件有点难读”。我想我会用一个python渲染器。谢谢。 – guettli