Dynamic Server Weight from a variable

Hey folks,

im trying to configure server weights from environment variables. I ended up with this but its not working (503) (stripped away not relevant parts of the config)

global
  set-var proc.percentage_new int("${PERCENTAGE_NEW}")
  set-var proc.percentage_old int("${PERCENTAGE_OLD}")

backend percentage_strategy
  option tcp-check

  cookie sticky_server_cookie insert indirect

  # old domain
  cookie old_domain
  server old_domain_percentage example.com:443 check ssl verify none weight var(proc.percentage_old)

  # new domain
  cookie new_domain
  server new_domain_percentage new-example.com:443 check ssl verify none weight var(proc.percentage_new)

googling doesnt give my any hint if thats possible. In the end i want to create an immutable docker image which i can reconfigure just by providing the weighted env vars:

docker run -e PERCENTAGE_NEW=5 -e PERCENTAGE_OLD=95 my-haproxy

also i thought basic arithmetics are possible so i only have to provide the PERCENTAGE_NEW and do a simple calculation for the old weight like

server old_domain_percentage example.com:443 check ssl verify none weight 100-var(proc.percentage_new)

but that doesnt even produce a valid config. I didnt wanted to go the lua route, if its not possible its ok to provide both variables (the math upfront isnt that hard i guess :wink: )

Indeed it is not possible to configure server weight using haproxy variables, as weight directive expects an integer

Available options are: env variables (may be used to populate haproxy config at startup), update from the cli/lua, or DNS-based discovery

For env variables, the correct syntax is:

server old_domain_percentage example.com:443 check ssl verify none weight "${ENV_VAR_NAME}"

See: https://docs.haproxy.org/dev/configuration.html#2.3

Hey @adarragon that how i figured it out myself. Sadly by only doing that, you loose “type validation” (setting the env variable to foo wouldnt result in an error but just in a “backend is unhealthy”.

That why i additionally added a type casting:

  # we source them from the environment here to actually typecheck them
  set-var proc.percentage_new int("${PERCENTAGE_NEW}")
  set-var proc.percentage_old int("${PERCENTAGE_OLD}")

so it immediatly fails on startup and it is safe to use the env-var as a weight for servers.