-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtraefik_hosts
executable file
·90 lines (74 loc) · 2.56 KB
/
traefik_hosts
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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
#!/usr/bin/env python3
import os
import sys
import docker
import socket
import logging
import argparse
def main():
parser = argparse.ArgumentParser()
parser.add_argument('-o', '--output', default='/etc/traefik_hosts')
parser.add_argument('-v', '--verbose', action='store_true', default=False)
args = parser.parse_args()
logging.basicConfig(
stream=sys.stderr,
format='%(levelname)s: %(message)s',
level=100000,
)
log = logging.getLogger('wait_for_services')
log.setLevel(logging.DEBUG if args.verbose else logging.INFO)
my_id = socket.gethostname()
client = docker.from_env()
label = None
for container in client.containers.list(all=True):
if container.id.startswith(my_id):
if 'com.docker.compose.project' in container.labels:
label = (
'com.docker.compose.project=%s'
) % container.labels['com.docker.compose.project']
break
if label is None:
log.critical(
'Cant find my project! Are you using me inside compose ?!')
return 1
containers = client.containers.list(filters={'label': label}, all=True)
containers = {
c.labels['com.docker.compose.service']: c
for c in containers
}
domains = set()
for service in list(containers):
container = containers[service]
if container.id.startswith(my_id):
containers.pop(service)
continue
for label, value in container.labels.items():
if label.startswith('traefik') and 'Host' in value:
if 'Host:' in value:
# v1
value = value.split('Host:', 1)[1]
value = value.split(';', 1)[0]
elif 'Host(' in value:
# v2
value = value.split('Host(', 1)[1]
value = value.split(')', 1)[0]
value = value.replace('`', '')
for name in value.split(','):
domains.add(name)
with open('/etc/hosts') as fd:
line = fd.readlines()[-1]
host = line.split()[0]
if os.path.isfile(args.output):
mode = 'a+'
else:
mode = 'w'
new_line = '{0} {1}'.format(host, ' '.join(sorted(list(domains))))
with open(args.output, mode) as fd:
fd.seek(0)
fd.truncate()
fd.write('127.0.0.1 localhost\n{0}\n'.format(new_line))
with open(args.output) as fd:
print(fd.read())
return 0
if __name__ == '__main__':
sys.exit(main())