In my overview post I showed a key/value structure in Consul that could be used to store metadata on each Node.

Now I’ll discusses how to put node metadata into the Consul key-store. For this example we have two web servers in the san datacenter (web1.web.san and web2.web.san) following the node naming hostid.hostgroup.datacenter.

Here is the key/value hierarchy we’ll create.

    /web1.web.san = {"hostgroup": "web"}
    /web2.web.san = {"hostgroup": "web"}

As I mentioned in my overview post there are several ways to create this structure. I go over a few ways below. Always test before running in production and ensure you have solid error handling.

curl -XPUT "http://localhost:8500/v1/kv/nagios/hosts/web1.web.san" -d '{"hostgroup":"web"}'
curl -XPUT "http://localhost:8500/v1/kv/nagios/hosts/web2.web.san" -d '{"hostgroup":"web"}'
HOSTS="web1.web.san web2.web.san"; \
for i in $HOSTS; \
    do curl -XPUT "http://localhost:8500/v1/kv/nagios/hosts/$i" -d '{"hostgroup":"web"}'; \



CONSUL PYTHON CLIENT (iterate over list from central server)

import consul

c = consul.Consul() # assumes
hosts = ['web1.web.san', 'web2.web.san']
for host in hosts:
    c.kv.put(key='nagios/hosts/%s' % host, value='{"hostgroup":"web"}')


CONSUL PYTHON CLIENT (parse hostgroup)

import consul

c = consul.Consul()
hosts = ['web1.web.san', 'web2.web.san']

for host in hosts:
    c.kv.put(key='nagios/hosts/%s' % host, value='{"hostgroup": "%s"}' % host.split('.')[1])


CONSUL PYTHON CLIENT (runs on each node)

The full key path is created and the value is written.

In part 2 I go over a simple Consul-Template structure to create a hosts.cfg file for Nagios.

Tagged on: