Provide multiple cfg files for haproxy loadbalancer

haproxyload balancing

My haproxy loadbalancer currently runs using a single config file, /etc/haproxy/haproxy.cfg:

ExecStart=/usr/sbin/haproxy-systemd-wrapper -f /etc/haproxy/haproxy.cfg -p /run/haproxy.pid $OPTIONS

I want to split the haproxy.cfg to several files with less content as some of the frontend and backend definitions could be generated using Ansible and templating. Can I just simply modify the -f argument to /etc/haproxy/*.cfg? Or should I rather point it to a dedicated directory e.g. /etc/haproxy/conf.d?

And a bonus question. Given the above is possible and I end up with a number of cfg files, with different frontend and backend stanzas, should I still include the global and defaults stanzas in every single cfg file?

Best Answer

You can point HAProxy to load configuration from a directory, depending on your HAProxy version that is. Also, yo do not need to enter multiple global sections in separate configuration files.

Check HAProxy Management documentation for your HAProxy server version for -f command line switch. Versions 1.6 and lower could only load a file, but you could add multiple -f <cfg1.cfg -f cfg2.cfg options. This is for eg. version 1.8:

  -f <cfgfile|cfgdir> : adds <cfgfile> to the list of configuration files to be
    loaded. If <cfgdir> is a directory, all the files (and only files) it
    contains are added in lexical order (using LC_COLLATE=C) to the list of
    configuration files to be loaded ; only files with ".cfg" extension are
    added, only non hidden files (not prefixed with ".") are added.
    Configuration files are loaded and processed in their declaration order.
    This option may be specified multiple times to load multiple files. See
    also "--". The difference between "--" and "-f" is that one "-f" must be
    placed before each file name, while a single "--" is needed before all file
    names. Both options can be used together, the command line ordering still
    applies. When more than one file is specified, each file must start on a
    section boundary, so the first keyword of each file must be one of
    "global", "defaults", "peers", "listen", "frontend", "backend", and so on.
    A file cannot contain just a server list for example.

But beware of how eg. multiple default section work:

A "defaults" section sets default parameters for all other sections following
its declaration. Those default parameters are reset by the next "defaults"
section.