Tomáš Fejfar Tomáš Fejfar - 5 months ago 36
Python Question

How to get IP address of hostname inside jinja template

Our saltstack is based on hostnames (webN., dbN., etc.). But for various things I need IPs of those servers. For now I had them stored in pillars, but the number of places I need to sync grows.

I tried to use publish + network.ip_addrs, but that kinda sucks, because it needs to do the whole salt-roundtrip just to resolve a hostname. Also it's dependent on the minions responding. Therefore I'm looking for a way to resolve hostname to IP in templates.

I assume that I could write a module for it somehow, but my python skills are very limited.

Answer Source

You could use a custom grain. Create file _grains/fqdn_ip.py in the state tree directory:

import socket

def fqdn_ip():
    return {
        'fqdn_ip': socket.gethostbyname(socket.getfqdn())
    }

In template:

{{ grains.fqdn_ip }}

Another way is use dnsutil module (requires dig command on minion):

{{ salt['dnsutil.A']('host.name.tld')[0] }}