Search code examples
pythondnsservice-discoveryconsul

How can I lookup dns service records in consul in python?


I am using consul to discover services in my environment. Consul's DNS service is running on a non-standard DNS port. My current solution is more of a work around and I would like to find the more pythonic way to do this:

digcmd='dig @127.0.0.1 -p 8600 chef.service.consul +short' # lookup the local chef server via consul
proc=subprocess.Popen(shlex.split(digcmd),stdout=subprocess.PIPE)
out, err=proc.communicate()
chef_server = "https://"+out.strip('\n')

Solution

  • You can use dnspython library to make queries using python.

    from dns import resolver
    
    consul_resolver = resolver.Resolver()
    consul_resolver.port = 8600
    consul_resolver.nameservers = ["127.0.0.1"]
    
    answer = consul_resolver.query("chef.service.consul", 'A')
    for answer_ip in answer:
        print(answer_ip)
    

    Using libraries like dnspython is more robust than invoking dig in a subprocess, because creating processes has memory and performance effects.