Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save oskarhane/9418693 to your computer and use it in GitHub Desktop.

Select an option

Save oskarhane/9418693 to your computer and use it in GitHub Desktop.
Create a HAProxy config file from a Docker container with a hostname as container name.
import subprocess
import sys
import re
conf_dir = '/etc/haproxy/conf.d/'
command = ["/usr/bin/docker ps | grep " + sys.argv[1]]
p = subprocess.Popen(command, stdout=subprocess.PIPE, shell=True)
output, err = p.communicate()
d_str = output.decode("utf-8")
ports = re.findall(':([0-9]+)->([0-9]+)', d_str)
domain = re.findall('\s([\S]+)\s*$', d_str)
f = open(conf_dir + domain[0], 'w+')
f.write('listen ' + domain[0] + "\n")
f.write("\tcontimeout 5000\n\tclitimeout 50000\n\tsrvtimeout 50000\n")
listen_str = ''
backend_str = ''
for i in range(len(ports)):
listen_str += '\tbind ' + '*:' + ''.join(ports[i][1]) + "\n"
listen_str += '\tacl port_' + str(i) + ' dst_port ' + ''.join(ports[i][1]) + "\n"
listen_str += '\tuse_backend backend_' + ''.join(ports[i][0]) + " if port_" + str(i) + "\n"
backend_str += "backend backend_" + ''.join(ports[i][0]) + "\n"
backend_str += "\tcontimeout 5000\n\tsrvtimeout 50000\n"
backend_str += "\tserver s1 127.0.0.1:" + ''.join(ports[i][0]) + " check\n"
f.write(listen_str)
f.write(backend_str)
f.close()
@oskarhane

Copy link
Copy Markdown
Author

FYI this does not work with multiple domains.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment