HAProxy community

Use set ssl cert with cert directory

I struggled quite a bit trying to figure out how to use the new directive to dynamically update certificates with HAProxy 2.1 when loading certificates from a directory. I think i got it right now, hope it is helpful to someone (and happy for feedback). The key point i missed for quite a while was that the certificate name for “set ssl cert” is the full path to the file and not just the filename.

haproxy.cfg excerpt:

global
    stats socket /var/run/haproxy mode 600 level admin
frontend https-in
    bind *:443 ssl crt /etc/ssl/private/

script to update certificates from letsencrypt certbot:

#!/bin/bash

set -e

LE_DIR=/etc/letsencrypt/live
HA_DIR=/etc/ssl/private
DOMAINS=$(ls ${LE_DIR})

# update certs for HA Proxy
for DOMAIN in ${DOMAINS}
do
  # also update the file in the filesystem for when haproxy restarts
  cat ${LE_DIR}/${DOMAIN}/fullchain.pem ${LE_DIR}/${DOMAIN}/privkey.pem | tee ${HA_DIR}/${DOMAIN}.pem
  echo -e "set ssl cert /etc/ssl/private/${DOMAIN}.pem <<\n$(cat ${HA_DIR}/${DOMAIN}.pem)\n" | socat stdio /var/run/haproxy
  echo -e "commit ssl cert /etc/ssl/private/${DOMAIN}.pem" | socat stdio /var/run/haproxy
done

Note: This script does not work when you dynamically add new domains, as those new domains will not be known to HAProxy. From HAProxy 2.2 on, there seem to be additional commands to cover that use case, but afaik you would need to know which domain is new vs which is already existing, to run the correct thing.

1 Like