Querying DNS in Puppet code

January 6, 2021 

I recently had to add access control rules to OpenVPN Access Server to permit certain groups to access certain IP addresses. As we manage our Access Server configurations with Puppet using puppet-openvpnas (by the author), we needed a way to parameterize the allowed IP addresses while keeping the Puppet code readable.

This is where puppet-dnsquery came really handy. It allows using data that's already available in DNS and using it in Puppet code. A simplistic example:

$servers = dns_lookup('server.example.org')

This will return an Array, for example ['']. Keep that in mind if the DNS record is supposed to contain only one entry you should use this instead:

$server = dns_lookup('server.example.org')[0]

Alternatively you can loop through all the returned entries and do something useful with them.

The downside is the dns_* functions is that they do not fail if nothing useful is returned. So, parameter validation needs to be done using assert_type:

$server = assert_type(Stdlib::IP::Address::V4, dns_lookup('server.example.org')[0])

If you have the DNS entries such as hostnames in Hiera you probably should not hardcode the values like above. Instead:

$server = assert_type(Stdlib::IP::Address::V4, dns_lookup(lookup('server_hostname', String))[0]) 

Check puppet-dnsquery and assert_type documentation for more details.

Samuli Seppänen
Samuli Seppänen
Author archive