5

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')
hughdbrown
  • 47,733
  • 20
  • 85
  • 108
wjimenez5271
  • 2,027
  • 2
  • 17
  • 24

2 Answers2

8

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.

Mohammad Salehe
  • 351
  • 1
  • 6
2

It's also quite easy to call the HTTP API with urllib.request:

import urllib.request

answer = urllib.request.urlopen("http://localhost:8500/v1/catalog/service/chef").read()

The basics of the HTTP API are documented in the Services Guide.

Joseph Holsten
  • 20,672
  • 6
  • 25
  • 29