HAProxy – Using Environmental Variables in haproxy.cfg

environment-variableshaproxy

Trying to figure out why environmental variables in haproxy.cfg aren't working in HA-Proxy version 1.5.2

on the command line, using Printenv I get a list of environmental variables like
FE_PORT_8000_TCP_ADDR=172.17.0.4

Which I need to use in the haproxy.cfg. According to this and the docs
How can I use environment variables in haproxy.conf using $FE_PORT_8000_TCP_ADDR or ${FE_PORT_8000_TCP_ADDR} should work. However that is not working.

In Haporxy.cfg hardcoding DOES work, and accessed in a browser it shows as expected:

backend FE
   # balance     roundrobin
    server      FE1 172.17.0.4:8000  maxconn 256

But environmental variable with same supposed value doesn't, in the browser it gives 503 Service Unavailable.

backend FE
   # balance     roundrobin
    server      FE1 $FE_PORT_8000_TCP_ADDR:8000  maxconn 256

Any ideas on what is being done wrong?

UPDATE: This person has what looks like the same issue
How can I use environment variables in haproxy.conf

Best Answer

Since you're stopping/starting with the service command, you need to specify the environment variables in your init script (e.g. /etc/init.d/haproxy on ubuntu) not in your interactive terminal session where you're controlling the service (service haproxy start). You can verify the environment variables available to a specific pid in the proc filesytem. If you check yours for haproxy, it'll likely be only TERM and LANG, because that's the only environment which gets passed via service to the init script (manpage for service).

# cat /proc/$(pgrep haproxy)/environ

If instead of starting daemonized haproxy from the init script you directly run haproxy you'll likely see the behavior you're looking for:

# haproxy -f /etc/haproxy/haproxy.cfg

To solve this, edit the init script /etc/init.d/haproxy and set your variables there:

export FE_PORT_8000_TCP_ADDR=172.17.0.4