DEV Community

Cover image for Automating HAProxy 3.3 and Data Plane API Deployment with Ansible
Patrick
Patrick

Posted on Originally published at blog.bsdserver.nl

Automating HAProxy 3.3 and Data Plane API Deployment with Ansible

HAProxy is one of the most powerful open-source load balancers, widely used for its reliability, security, and performance. The Data Plane API adds a REST API to manage its configuration. Installing both by hand means a repository, a pinned package, a binary from GitHub, two config files and a systemd unit, on every load balancer.

This post walks through one Ansible playbook that does all of that, from the official HAProxy repositories, and gives the same result on every run.

Why Ansible for this?

  • Repeatable - Every load balancer gets the same packages, files and service
  • Version control - Change haproxy_version or dataplaneapi_version and rerun to upgrade
  • Idempotent - A second run reports no changes, so you can run it at any time

When to use it

  • Use it for more than one load balancer, or for one you want to rebuild quickly.
  • Skip it for a single throwaway test box; the manual steps in the Data Plane API post are quicker.

Architecture Overview

Component Comes from Job
HAProxy vbernat/haproxy-X.Y PPA (Ubuntu) or haproxy.debian.net (Debian) The load balancer.
haproxy.cfg Template haproxy.cfg.j2, written once Base config with the stats socket and the API userlist. After that the Data Plane API owns it.
Data Plane API GitHub release binary REST API that edits haproxy.cfg and reloads HAProxy.
dataplaneapi.yaml Template dataplaneapi.yaml.j2 API listen address, userlist and reload commands.
dataplaneapi.service Inline in the playbook Starts the API at boot.

The flow: add the repository → install HAProxy → write haproxy.cfg (first run only) → install the API binary → write its config → start the service.

Prerequisites

Before running this playbook, ensure that:

  • You have an Ansible control node with SSH access to the target server.
  • The target server is running a Debian-based OS (Ubuntu/Debian).
  • You have sudo privileges on the target machine.
  • The target can reach the official HAProxy package repositories: the vbernat/haproxy-X.Y PPA on Ubuntu and haproxy.debian.net on Debian. The distribution's own haproxy package is usually a few branches behind.

Choosing an HAProxy branch

HAProxy has two kinds of stable branches:

Branch Maintained Use it for
LTS (3.2, 3.4) Five years Long-lived installs
Other stable (3.3) About a year The newest features, if you upgrade often

This playbook uses 3.3, the newest branch the PPA builds for Ubuntu 24.04 (3.4 LTS is only built for Ubuntu 26.04 and Debian 13). For a long-lived Ubuntu 24.04 install, set haproxy_version: "3.2" to stay on an LTS branch.

Ansible Playbook for HAProxy and Data Plane API Installation

Below is the complete Ansible playbook to install and configure HAProxy along with the Data Plane API.

The variables at the top:

Variable Default What it sets
haproxy_version "3.3" The repository branch and the pinned package version
dataplaneapi_version "3.4.7" The API release from GitHub. Changing it upgrades or downgrades.
dataplaneapi_user, dataplaneapi_password_hash admin, a placeholder The API login. The password as a SHA-512 crypt hash from openssl passwd -6. Keep it in Ansible Vault.
api_bind_address, api_port 127.0.0.1, 5555 Where the API listens. Plain HTTP, so localhost only.
haproxy_socket /run/haproxy/admin.sock HAProxy's runtime socket

What the tasks do, in order:

Tasks What they do Why this way
Install python3-debian Dependency deb822_repository needs it on the target
Keyring, stat, get_url Download the repository signing key Only once: the keyserver does not always return identical keys, so a plain download would report a change
deb822_repository (twice) Add the PPA on Ubuntu or haproxy.debian.net on Debian The suite comes from the OS release, so one playbook fits both
apt haproxy=X.Y.* Install HAProxy Pins the branch. The package cache is only refreshed when the repository was just added.
Socket directory, marker stat, existing-config check, haproxy.cfg template, password line, marker file Base configuration, written once After the first run the Data Plane API owns haproxy.cfg, so later runs leave it alone (below). The handler reloads HAProxy, no restart.
--version check, unarchive Install the API binary Only when the installed version differs from dataplaneapi_version
dataplaneapi.yaml template API configuration root and 0600, the same as the API writes it. A change restarts the API.
systemd unit, systemd Start the API now and at boot daemon_reload picks up a new or changed unit
---
- name: Install and Configure HAProxy with Data Plane API
  hosts: your_target_host
  become: yes
  vars:
    haproxy_version: "3.3"
    dataplaneapi_version: "3.4.7"
    haproxy_user: "haproxy"
    haproxy_group: "haproxy"
    dataplaneapi_user: "admin"
    # openssl passwd -6 'your-secure-password'
    dataplaneapi_password_hash: "$6$replace$with-openssl-passwd-6-output"
    # Plain HTTP: keep it on localhost
    api_bind_address: "127.0.0.1"
    api_port: 5555
    haproxy_socket: "/run/haproxy/admin.sock"
    haproxy_config_file: "/etc/haproxy/haproxy.cfg"
    haproxy_bootstrap_marker: "/etc/haproxy/.haproxy-cfg-bootstrapped"
    dataplaneapi_config_file: "/etc/haproxy/dataplaneapi.yaml"

  tasks:
    # deb822_repository needs python3-debian on the target
    - name: Install python3-debian
      apt:
        name: python3-debian
        state: present
        update_cache: yes
        cache_valid_time: 3600

    # Download the signing keys only once: the keyserver ignores
    # If-Modified-Since and does not always return byte-identical keys, so a
    # plain get_url would report a change on some runs
    - name: Ensure /etc/apt/keyrings exists
      file:
        path: /etc/apt/keyrings
        state: directory
        mode: '0755'

    - name: Check for the HAProxy repository signing key
      stat:
        path: "/etc/apt/keyrings/{{ 'haproxy-ppa.asc' if ansible_facts['distribution'] == 'Ubuntu' else 'haproxy.debian.net.gpg' }}"
      register: haproxy_repo_key

    - name: Download the HAProxy PPA signing key (Ubuntu)
      get_url:
        url: "https://keyserver.ubuntu.com/pks/lookup?op=get&search=0x3D653970FBAB0A890E4E4E9A0F14D8B0CF4EFE96"
        dest: /etc/apt/keyrings/haproxy-ppa.asc
        mode: '0644'
      when: ansible_facts['distribution'] == "Ubuntu" and not haproxy_repo_key.stat.exists

    - name: Download the haproxy.debian.net signing key (Debian)
      get_url:
        url: "https://haproxy.debian.net/haproxy-archive-keyring.gpg"
        dest: /etc/apt/keyrings/haproxy.debian.net.gpg
        mode: '0644'
      when: ansible_facts['distribution'] == "Debian" and not haproxy_repo_key.stat.exists

    - name: Add HAProxy {{ haproxy_version }} Repository (Ubuntu PPA)
      deb822_repository:
        name: haproxy-{{ haproxy_version }}
        types: deb
        uris: "https://ppa.launchpadcontent.net/vbernat/haproxy-{{ haproxy_version }}/ubuntu"
        suites: "{{ ansible_facts['distribution_release'] }}"
        components: main
        signed_by: /etc/apt/keyrings/haproxy-ppa.asc
      register: haproxy_repo_ubuntu
      when: ansible_facts['distribution'] == "Ubuntu"

    - name: Add HAProxy {{ haproxy_version }} Repository (haproxy.debian.net)
      deb822_repository:
        name: haproxy-{{ haproxy_version }}
        types: deb
        uris: "http://haproxy.debian.net"
        suites: "{{ ansible_facts['distribution_release'] }}-backports-{{ haproxy_version }}"
        components: main
        signed_by: /etc/apt/keyrings/haproxy.debian.net.gpg
      register: haproxy_repo_debian
      when: ansible_facts['distribution'] == "Debian"

    - name: Install HAProxy {{ haproxy_version }}
      apt:
        name: haproxy={{ haproxy_version }}.*
        state: present
        update_cache: "{{ haproxy_repo_ubuntu is changed or haproxy_repo_debian is changed }}"

    - name: Ensure HAProxy socket directory exists
      file:
        path: "{{ haproxy_socket | dirname }}"
        state: directory
        owner: "{{ haproxy_user }}"
        group: "{{ haproxy_group }}"
        mode: '0755'

    # Bootstrap only: write haproxy.cfg once, then the Data Plane API owns it.
    # The haproxy package ships its own haproxy.cfg, so force: false alone
    # would never write the template; the marker records the first write.
    - name: Check whether haproxy.cfg was bootstrapped
      stat:
        path: "{{ haproxy_bootstrap_marker }}"
      register: haproxy_bootstrapped

    # A host set up before the marker existed already has the API userlist,
    # which the package default never has: adopt it, don't overwrite it
    - name: Check for a haproxy.cfg the Data Plane API already manages
      command: grep -q '^userlist dataplaneapi$' {{ haproxy_config_file }}
      register: haproxy_managed_cfg
      changed_when: false
      failed_when: haproxy_managed_cfg.rc > 1
      when: not haproxy_bootstrapped.stat.exists

    - name: Create the initial HAProxy configuration
      template:
        src: haproxy.cfg.j2
        dest: "{{ haproxy_config_file }}"
        owner: "{{ haproxy_user }}"
        group: "{{ haproxy_group }}"
        mode: '0644'
        validate: haproxy -c -f %s
      when:
        - not haproxy_bootstrapped.stat.exists
        - haproxy_managed_cfg.rc != 0
      notify: reload haproxy

    # The one line Ansible keeps managing: rotates the password and replaces
    # an old plaintext insecure-password. Two spaces, as the API writes it.
    - name: Set the Data Plane API user's password hash
      lineinfile:
        path: "{{ haproxy_config_file }}"
        regexp: '^\s+user {{ dataplaneapi_user }} (insecure-)?password '
        line: "  user {{ dataplaneapi_user }} password {{ dataplaneapi_password_hash }}"
        insertafter: '^userlist dataplaneapi$'
        validate: haproxy -c -f %s
      no_log: true
      notify:
        - reload haproxy
        - restart dataplaneapi

    - name: Mark haproxy.cfg as owned by the Data Plane API
      copy:
        dest: "{{ haproxy_bootstrap_marker }}"
        content: |
          haproxy.cfg was bootstrapped by Ansible and is now managed by the Data Plane API.
          Delete this file to let the playbook write its template again.
        mode: '0644'
        force: false

    # Compare the installed version with the wanted one, so that changing
    # dataplaneapi_version upgrades (or downgrades) an existing install
    - name: Check installed Data Plane API version
      command: /usr/local/bin/dataplaneapi --version
      register: dataplaneapi_installed
      changed_when: false
      failed_when: false

    - name: Download HAProxy Data Plane API {{ dataplaneapi_version }}
      unarchive:
        src: "https://github.com/haproxytech/dataplaneapi/releases/download/v{{ dataplaneapi_version }}/dataplaneapi_{{ dataplaneapi_version }}_linux_x86_64.tar.gz"
        dest: /usr/local/bin
        remote_src: yes
        include:
          - dataplaneapi
        mode: '0755'
      when: dataplaneapi_installed.stdout is not search('v' ~ (dataplaneapi_version | regex_escape) ~ ' ')
      notify: restart dataplaneapi

    - name: Create Data Plane API Configuration
      template:
        src: dataplaneapi.yaml.j2
        dest: "{{ dataplaneapi_config_file }}"
        # root and 0600, like the service: Data Plane API rewrites this
        # file with these permissions every time it starts
        owner: root
        group: root
        mode: '0600'
      notify: restart dataplaneapi

    - name: Create systemd service for Data Plane API
      copy:
        dest: /etc/systemd/system/dataplaneapi.service
        content: |
          [Unit]
          Description=HAProxy Data Plane API
          After=network.target haproxy.service

          [Service]
          # -f is the Data Plane API config; --config-file is haproxy.cfg.
          # Runs as root: it rewrites haproxy.cfg and calls systemctl reload.
          ExecStart=/usr/local/bin/dataplaneapi -f {{ dataplaneapi_config_file }}
          Restart=always

          [Install]
          WantedBy=multi-user.target
      notify: reload systemd

    - name: Enable and start Data Plane API service
      systemd:
        name: dataplaneapi
        enabled: yes
        state: started
        daemon_reload: yes

  handlers:
    - name: reload haproxy
      service:
        name: haproxy
        state: reloaded

    - name: reload systemd
      command: systemctl daemon-reload

    - name: restart dataplaneapi
      service:
        name: dataplaneapi
        state: restarted
Enter fullscreen mode Exit fullscreen mode

HAProxy Configuration Template (haproxy.cfg.j2)

A minimal starting point. The parts the API needs:

  • stats socket ... level admin: the runtime socket for changes without a reload.
  • userlist dataplaneapi: the API login. password takes a crypt hash, so the password itself is not in haproxy.cfg.
  • frontend http-in / backend servers: a placeholder application to replace with your own.

The playbook writes this file only once; after that the Data Plane API owns haproxy.cfg:

Run What happens to haproxy.cfg Why
First The template replaces the package's default file, HAProxy reloads No marker file yet
Later Left alone, also after changes through the API (changed=0) The marker exists, so the template is skipped
First run on a host set up by an older version of this playbook Left alone; only the password line changes No marker, but haproxy.cfg already has userlist dataplaneapi, so the host is adopted
Rebuild from the template Delete /etc/haproxy/.haproxy-cfg-bootstrapped and run again Overwrites everything the API changed
  • Why a marker: force: false alone is not enough. The haproxy package already installs an /etc/haproxy/haproxy.cfg, so the template would never be written.
  • Why the password line is separate: it is the only line Ansible keeps managing. Changing dataplaneapi_password_hash rotates the API password, and an older version's plaintext insecure-password line is replaced by the hash.
  • Why two spaces: the Data Plane API rewrites haproxy.cfg with two-space indentation. With four, every run after an API change would report the line as changed.
global
    log /dev/log local0
    log /dev/log local1 notice
    stats socket {{ haproxy_socket }} mode 660 level admin
    user {{ haproxy_user }}
    group {{ haproxy_group }}

defaults
    log     global
    mode    http
    option  httplog
    option  dontlognull
    timeout connect 5000ms
    timeout client  50000ms
    timeout server  50000ms

userlist dataplaneapi
  user {{ dataplaneapi_user }} password {{ dataplaneapi_password_hash }}

frontend http-in
    bind *:80
    default_backend servers

backend servers
    server server1 127.0.0.1:8000 maxconn 32
Enter fullscreen mode Exit fullscreen mode

Data Plane API Configuration Template (dataplaneapi.yaml.j2)

The Data Plane API authenticates against the dataplaneapi userlist in haproxy.cfg. It also rewrites this file in its own normalized form every time it starts, so the template is written in exactly that form; otherwise every playbook run would report it as changed.

  • userlist: dataplaneapi: use the userlist from haproxy.cfg instead of users in this file.
  • reload_cmd / restart_cmd with reload_strategy: custom: the API reloads HAProxy through systemd.
  • reload_delay: 5: at most one reload every 5 seconds.
  • log_targets to stdout: the API log ends up in the journal (journalctl -u dataplaneapi).
config_version: 2
name: {{ inventory_hostname }}
dataplaneapi:
  host: {{ api_bind_address }}
  port: {{ api_port }}
  advertised:
    api_address: ""
    api_port: 0
  scheme:
  - http
  userlist:
    userlist: dataplaneapi
    userlist_file: ""
  transaction:
    transaction_dir: /tmp/haproxy
haproxy:
  config_file: {{ haproxy_config_file }}
  haproxy_bin: /usr/sbin/haproxy
  reload:
    reload_delay: 5
    reload_cmd: systemctl reload haproxy
    restart_cmd: systemctl restart haproxy
    reload_strategy: custom
log_targets:
- log_to: stdout
  log_level: info
Enter fullscreen mode Exit fullscreen mode

Security Considerations

  • Store the hash in Ansible Vault, not in the playbook. Generate it with openssl passwd -6 'your-secure-password' (or mkpasswd -m sha-512 from the whois package).
  • Keep api_bind_address on 127.0.0.1. The API speaks plain HTTP; on 0.0.0.0 it sends the password unencrypted over the network. Reach it with an SSH tunnel (ssh -L 5555:127.0.0.1:5555 lb1), or put TLS in front as in the Data Plane API post.

Automate it

The playbook from this post, split into roles, plus Terraform code for the machine, is on GitHub:
pderuiter/blog-haproxy-ansible. It creates an Ubuntu 24.04 VM and installs HAProxy and the Data Plane API exactly as above; set the API password in the vault and run ansible-playbook site.yml.

Conclusion

One playbook installs HAProxy and the Data Plane API the same way on every machine, and a version bump is a variable change.

Next: use the API to manage backends (Data Plane API post) or to fill them from Consul (Consul post).


Originally published on A DevOps Blog.

Top comments (0)