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.
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
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] }}
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
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] }}
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With