forked from giantmonkey/docker-tools
-
Notifications
You must be signed in to change notification settings - Fork 0
/
dt-dns-config
executable file
·60 lines (44 loc) · 1.85 KB
/
dt-dns-config
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
#!/usr/bin/python
import argparse
import socket
import docker
def parse_arguments():
class DefaultList(list):
def __copy__(self):
return []
parser = argparse.ArgumentParser(description="Rewrite the DNS config file for docker containers.", formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument("--hosts-file", type=str, default="/etc/hosts.docker", help="output file for hosts")
parser.add_argument("--domain", type=str, default=DefaultList([socket.getfqdn()]), action="append", dest="domains", help="domain name to append to each host. may be specified multiple times")
parser.add_argument("--dry-run", action="store_true", help="only print to stdout instead of writing to file")
return parser.parse_args()
def get_docker_hosts(args):
client = docker.Client()
containers = client.containers()
hosts = []
for container in containers:
inspect = client.inspect_container(container["Id"])
name = inspect["Name"].lstrip("/")
host = {}
host["ip"] = inspect["NetworkSettings"]["IPAddress"]
host["names"] = set()
host["names"].add(name)
for domain in args.domains:
host["names"].add(name + "." + domain)
if inspect["Config"]["Hostname"]:
host["names"].add(inspect["Config"]["Hostname"])
hosts.append(host)
return hosts
def write_hosts_file(args, hosts):
name_widths = [len(name) for host in hosts for name in host["names"]]
max_name_width = max(name_widths) + 4
lines = ["%(ip)-20s%(names)s" % {"ip": host["ip"], "names": "".join(["%-*s" % (max_name_width, name) for name in host["names"]])} for host in hosts]
output = "\n".join(lines)
if args.dry_run:
print output
else:
with open(args.hosts_file, "w") as f:
f.write(output)
print "Replaced DNS config in %s" % args.hosts_file
args = parse_arguments()
hosts = get_docker_hosts(args)
write_hosts_file(args, hosts)