Skip to content

Instantly share code, notes, and snippets.

@roguh
Last active July 31, 2023 22:07
Show Gist options
  • Save roguh/34e93d2568d637be93b2c72695b46abd to your computer and use it in GitHub Desktop.
Save roguh/34e93d2568d637be93b2c72695b46abd to your computer and use it in GitHub Desktop.
Lua resolve hostname with resty.dns.resolver
function resolve_hostname(hostname)
local dns_resolver_lib = require("resty.dns.resolver")
local dns_resolver, dns_resolver_err = dns_resolver_lib:new({
-- Kubernetes default nameserver IP
-- If your hostnames are public, try Google's DNS nameserver 8.8.8.8
nameservers = {"kube-dns.kube-system.svc.cluster.local"},
-- 250 milliseconds
timeout = 250,
retrans = 2
})
if not dns_resolver then
ngx.log(
ngx.ERR,
"Failed to instantiate lua-resty-dns-resolver",
dns_resolver_err
)
return nil
end
local dns_answers, dns_err, dns_tries = dns_resolver:query(hostname, nil, {})
if not dns_answers then
ngx.log(
ngx.ERR,
"Failed to query DNS server: ",
dns_err,
table.concat(dns_tries, "\n ")
)
return nil
end
if dns_answers.errcode then
ngx.log(
ngx.ERR,
"DNS server returned error code ",
dns_answers.errcode,
": ",
dns_answers.errstr
)
return nil
end
for i, answer in ipairs(dns_answers) do
local ip = answer.address or answer.cname
if ip ~= nil then
return ip
end
end
return nil
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment