Amadan
Amadan

Reputation: 198314

Complex filtering in Ansible/Jinja2

I am pretty new to Jinja2, and I'm wondering how to achieve this.

Say I have the following vars:

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

I want to create a symlink /data/foo1 to /disks/foo1 and /data/foo2 to /disks/foo2, but only on foo server; on other servers, make symlinks to their respective exports. So I thought file status=link with_items=... would be the correct thing to do. In Python, I can get the array I need using the following logic:

[
    { '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()'
]

I don't know how to do this in Jinja2. I wanted to do something like

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

but that doesn't work. Would I need to create a plugin for this logic? Or is my approach all wrong and I should rethink the structure of my servers data?

Upvotes: 1

Views: 892

Answers (1)

Konstantin Suvorov
Konstantin Suvorov

Reputation: 68269

Answer from my comment:

Usually you want to use inventory_hostname variable – it is what you use as host name in inventory.
servers[ansible_hostname] will access servers' key with name of ansible_hostname's value.

Just for curiosity, you can check out this (complex filter chain) and this (runtime object construction).

Upvotes: 2

Related Questions