Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 588
Tomáš Fejfar Avatar asked Aug 21 '13 14:08

Tomáš Fejfar


4 Answers

Reading through the ansible documentation, I found a much simpler solution. Here are my results.

enter the following into the template:

lookup hostname: {{ lookup('dig', 'google.ca.') }}

My jinja2 template:

# mytemplate.j2
## lookup directly
lookup hostname: {{ lookup('dig', 'google.ca.') }}

## in a variable
{% set fqdn = 'google.ca' %}
lookup hostname: {{ lookup('dig', fqdn) }}

Result:

# mytemplate.j2
## lookup directly
lookup hostname: 172.217.2.163

## in a variable
lookup hostname: 172.217.2.163
like image 165
Bhav Avatar answered Sep 23 '22 08:09

Bhav


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] }}
like image 12
kubus Avatar answered Nov 04 '22 08:11

kubus


I've see this: http://cnygaard.blogspot.com.es/2012/11/how-to-template-eth0-address-with.html

This is the easy way that I've found.

#init.sls:

...
...

/etc/swift/proxy-server.conf:              
   file:
     - managed                              
     - source: salt://swift/proxy-server.conf
     - template: jinja
     - context:
         proxy_ip: {{ salt['network.interfaces']()['eth0']['inet'][0]['address'] }}

And then:

#In proxy-server.conf

...

[filter:cache]
use = egg:swift#memcache
memcache_servers = {{ proxy_ip }}:11211
like image 4
José Ibañez Avatar answered Nov 04 '22 10:11

José Ibañez


This is a very old post, but it is highly ranked in Google for getting the ipv4 address. As of salt 2015.5.8, the best way to get the primary ipv4 address is {{ grains['ipv4'][0] }}.

like image 4
David Meiser Avatar answered Nov 04 '22 08:11

David Meiser