2016-11-07 66 views
0

我对Jinja2很新,我想知道如何实现这一点。Ansible/Jinja2中的复杂过滤

说我有以下vars

--- 
servers: 
    192.168.0.1: 
    names: 
     - foo.example.com 
     - foo 
    exports: 
     data: 
     foo1: /disks/foo1 
     foo2: /disks/foo2 
    192.168.0.2: 
    ... 

我想创建一个符号链接/data/foo1/disks/foo1/data/foo2/disks/foo2,但只有foo服务器上;在其他服务器上,使符号链接到它们各自的导出。所以我认为file status=link with_items=...将是正确的做法。在Python中,我可以使用以下逻辑得到我需要的数组:

[ 
    { 'mount': mount, 'export': export } 
    for ip, server in servers.iteritems() 
    if ansible_hostname in server['names'] 
    and 'exports' in server 
    and 'data' in server['exports'] 
    for mount, export in server['exports']['data'].iteritems()' 
] 

我不知道如何在Jinja2中执行此操作。我想要做类似

{{ servers | select('ansible_hostname in self.names') | ... }} 

但这并不起作用。我需要为这个逻辑创建一个插件吗?或者,我的方法都是错误的,我应该重新考虑我的servers数据的结构?从我的评论

+0

为什么不直接遍历'servers [ansible_hostname] .exports.data'? –

+0

@KonstantinSuvorov:因为我不知道'ansible_hostname'采用哪种形式。现在我说出来了,这听起来很愚蠢 - 这可能是我放入“库存”的东西,对吧?我会尽力和明天一起玩。同时我仍然对Jinja2中的复杂转变感到好奇。 – Amadan

+0

通常你想使用'inventory_hostname'变量 - 这是你在库存中用作主机名的东西。 'servers [ansible_hostname]'将访问名为'ansible_hostname'的值的'servers'键。只是为了好奇,你可以查看[this](http://stackoverflow.com/a/40395995/2795592)和[this](http://stackoverflow.com/a/40036807/2795592)。 –

回答

1

答:

通常要使用​​变量 - 它是你的主机名库存使用什么。
servers[ansible_hostname]将访问servers的密钥,其名称为ansible_hostname的值。

只是为了好奇,您可以查看this(复杂的过滤器链)和this(运行时对象构造)。