1

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?

Amadan
  • 191,408
  • 23
  • 240
  • 301
  • Why not just loop over `servers[ansible_hostname].exports.data`? – Konstantin Suvorov Nov 07 '16 at 09:14
  • @KonstantinSuvorov: because I don't know which form `ansible_hostname` takes. Now that I say it out lout it sounds stupid - it is probably what I put into `inventory`, right? I'll try and play with that tomorrow; in the meantime I'm still curious about complex transformations in Jinja2. – Amadan Nov 07 '16 at 09:28
  • 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](http://stackoverflow.com/a/40395995/2795592) and [this](http://stackoverflow.com/a/40036807/2795592). – Konstantin Suvorov Nov 07 '16 at 09:36
  • Welp, no more answers. @KonstantinSuvorov: If you submit that as an answer, I'll accept it. – Amadan Nov 08 '16 at 07:48

1 Answers1

2

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).

Community
  • 1
  • 1
Konstantin Suvorov
  • 65,183
  • 9
  • 162
  • 193