A collection of task oriented solutions in Puppet

 

Lookup DNS records in Puppet

Challenge

You want to use values from DNS in your puppet code

Solution

# install the dns query module
$ sudo /opt/puppetlabs/bin/puppet module install dalen-dnsquery

...
Notice: Installing -- do not interrupt ...
/etc/puppetlabs/code/environments/production/site
  dalen-dnsquery (v3.0.0)
...
class a_record {

  $pcb_ip = dns_a('www.puppetcookbook.com')

  notify { "Puppetcookbook resolves to ${pcb_ip[0]}": }

}
Notice: Puppetcookbook is at 213.138.113.230

Explanation

Performing DNS queries from your puppet code and using the results in your manifests can help bridge the gap between entirely static configuration values and a slightly more dynamic environment. It's not an everyday task but it's good to know that with the addition of the very focused dalen-dnsquery module the capability is there if you need it. As you've grown used to, first we install the module:

# install the dns query module
$ sudo /opt/puppetlabs/bin/puppet module install dalen-dnsquery

...
Notice: Installing -- do not interrupt ...
/etc/puppetlabs/code/environments/production/site
  dalen-dnsquery (v3.0.0)
...

DNSQuery adds a number of DNS resolution functions to your puppet install that allow you to lookup a variety of record types. As this code is implemented as functions it's important to note that the resolution takes place on the master, not the agents. In our example below we'll resolve the A record for www.puppetcookbook.com.

class a_record {

  $pcb_ip = dns_a('www.puppetcookbook.com')

  notify { "Puppetcookbook resolves to ${pcb_ip[0]}": }

}
Notice: Puppetcookbook is at 213.138.113.230

In this basic example we output the returned value to the console but it could easily be used to add a local host entry or a setting in a config file. While this module isn't a replacement for a robust service discovery system, in more mature enterprise environments with fewer changes, it can provide just enough dynamism to prove useful.

What happens if the record we're asking for doesn't exist? You can either handle this in your own code or add a lambda to the function call to return a default value if the resolution fails.

class test_dns_default {

  $pcb_ip = dns_a('fakesubdomain.puppetcookbook.com') || { ['127.0.0.1'] }

  notify { "Puppetcookbook is at ${pcb_ip[0]}": }

}
Notice: Puppetcookbook is at 127.0.0.1

See also