Skip to content

This is the multi-page printable view of this section. .

Return to the regular view of this page.

Ansible Deployment

Manage pgcli resources declaratively with the bundled Ansible playbooks — instances, replicas, add-ons, Patroni HA clusters, and S3 stores

The ansible/ directory in the pgcli repository turns the CLI into a declarative deployment tool. Instead of running pg create, pg addon install and pg ha create by hand on every host, you describe the desired state in group_vars/ and run one playbook. Re-running the playbook converges the hosts to that state and is safe to repeat.

What it manages

Resource Ansible input Role
pg binary, podman, host config pgcli_* variables in group_vars/all pgcli
PostgreSQL instances and read-only replicas pgcli_instances pg_instance
Host processes (webhook receivers, …) pgcli_daemons pg_daemon
Add-ons (etcd, pgbouncer, MinIO, …) pgcli_addons pg_addon
Patroni HA clusters and their etcd DCS pg_ha_clusters, pgcli_addons (etcd) pg_ha, pg_addon
HAProxy in front of HA clusters pg_ha_haproxy pg_ha_haproxy
Standalone S3-compatible stores for backups pgcli_s3_* pg_s3
pg http file servers for offline asset distribution pgcli_http_servers pg_http

Every mutating task is guarded by the current pgcli config and container state, so an unchanged host reports ok rather than changed.

Business scenarios are separated by inventory group and group_vars file: standalone, same-host replica, cross-host replica, instance plus add-ons, Patroni HA, S3 storage, and per-type add-on groups. Enable one scenario group at a time; Setup has the mapping table.

Repository layout

ansible/
├── ansible.cfg.example      # copy to ansible.cfg
├── hosts.ini.example        # copy to hosts.ini (gitignored)
├── pyproject.toml           # pinned Ansible via uv
├── group_vars/
│   ├── all/main.yml.example        # global defaults: install, config, instance defaults
│   ├── single/ samehost/ crosshost/  # one deployment mode per group
│   ├── observable/                   # monitoring + alerting scenario (exporters, Prometheus, Alertmanager)
│   ├── minio_s3/ silo_s3/ rustfs_s3/ # S3 store types
│   ├── addon_<type>_single/         # one group per standalone add-on
│   ├── addon_<type>_cluster/        # one group per multi-host add-on cluster
│   ├── ha_etcd/ ha_cluster/          # shared DCS and Patroni members
│   └── http/                        # pg http file server declarations
├── host_vars/               # optional per-host overrides
├── misc/
│   ├── prometheus/          # Prometheus alert rule files
│   └── webhook/             # Alertmanager webhook receiver
├── playbooks/
│   ├── apply.yaml           # install + instances + daemons + add-ons + HA
│   ├── deploy-http.yaml     # pg http file servers
│   ├── deploy-s3.yaml       # standalone S3 store
│   ├── ha-status.yaml       # read-only Patroni/HAProxy status
│   └── ping.yaml            # connectivity smoke test
└── roles/                   # pgcli, pg_instance, pg_daemon, pg_addon, addon_cluster_shared, pg_ha, pg_ha_haproxy, pg_s3, pg_http

Pages

Page What it covers
Quick deploy Copy-paste commands: one host, one standalone instance, from clone to pg list
Setup and example files Which *.example file becomes which live file, hosts.ini groups, group_vars fields, first run
Offline and air-gapped installs LAN HTTP server: image manifest and lazy loading, pg/podman binaries, runtime host binaries and DocumentDB DEBs
Offline image server Export all images from pgcli_images with export-images.sh, serve them with pg http, wire up Ansible
HTTP file server The pg_http role and deploy-http.yaml: every pg http parameter (TLS, auth, write modes, autostart) plus offline binary sync
Egress proxy Forward proxy for isolated data centers: Privoxy add-on, global variables, NO_PROXY, manual SSH usage, verification
Playbooks ping.yaml, apply.yaml, resources.yaml, deploy-s3.yaml, ha-status.yaml, passwords.yaml: tags, --limit, idempotency, lifecycle orders
Instances and replicas The single/samehost/crosshost example files and every pgcli_instances field
Observability deployment Monitoring and alerting for many machines: exporters, Prometheus, rules, Alertmanager, webhook daemon, Grafana
Add-ons addon_<type>_<mode> entries: install/remove, instance-scoped add-ons, etcd
Add-on clusters Multi-host add-on clusters: one inventory group per type, shared secrets/CA, quorum layouts, lifecycle
HA clusters ha_etcd/ha_cluster example files, pg_ha_clusters, HAProxy, state-driven destroy
S3 storage Store-type example files, deploy-s3.yaml options, using the store as a backup target

1 - Quick deploy

Copy-paste commands to deploy one standalone PostgreSQL instance on one host

Replace myproj, db-01 and the SSH address, then run on the control node:

myproj=xx
git clone --depth 1 https://github.com/mars-base/pgcli-ansible.git ansible-${myproj}
cd ansible-${myproj}
uv sync
cp ansible.cfg.example ansible.cfg

cat > hosts.ini <<'EOF'
[single]
db-01 ansible_host=192.0.2.10 private_ip=192.0.2.10 ansible_user=root ansible_port=22

[single:vars]
ansible_group_priority=20
EOF

cp group_vars/all/main.yml.example group_vars/all/main.yml
cat > group_vars/single/main.yml <<'EOF'
pgcli_config_overrides:
  namespace: dev

pgcli_instances:
  - name: pg_single
    host: db-01
    state: started
    autostart: true
EOF

uv run ansible-playbook playbooks/ping.yaml --limit single
uv run ansible-playbook playbooks/apply.yaml --limit single

uv run ansible single -m command -a 'pg list'
uv run ansible single -m command -a 'pg exec pg_single -c "SELECT version();"'

apply.yaml installs pgcli, initializes the host config, and creates pg_single; re-running it is idempotent.

For more deployment examples, see hosts.ini.example and the main.yml.example file under the matching group_vars/<group>/ directory.

2 - Setup and example files

Turn the shipped *.example files into a working Ansible inventory and variable set, then verify connectivity

The repository never commits environment-specific files. Everything is prepared by copying a checked-in *.example file to its live name, then editing it. The live copies are ignored by ansible/.gitignore.

Prerequisites

  • A Linux or macOS control node with uv.
  • SSH access to every managed host. The examples use ansible_user=root. Rootless deployments keep the SSH account separate from the unprivileged deployment account; the SSH account still needs sudo because host preparation always runs through become.
  • Target hosts run a supported Linux distribution; podman is installed by the pgcli role when missing.

Prepare the environment

cd ansible
uv sync

pyproject.toml pins Ansible (ansible-core 2.18); always run playbooks through uv run so the pinned environment is used.

Copy the example files

Example (committed) Live file (gitignored) Purpose
ansible.cfg.example ansible.cfg Inventory path, roles path, fact cache, var/ansible.log, SSH pipelining
hosts.ini.example hosts.ini Inventory: deployment-mode groups, S3 groups, HA role groups
group_vars/all/main.yml.example group_vars/all/main.yml Install source/version, config paths, namespaces, instance defaults
group_vars/single/main.yml.example group_vars/single/main.yml Standalone instance mode
group_vars/samehost/main.yml.example group_vars/samehost/main.yml Primary + same-host replica mode
group_vars/crosshost/main.yml.example group_vars/crosshost/main.yml Primary + cross-host replica mode, S3 backup vars
group_vars/instance_addon_mixed/main.yml.example group_vars/instance_addon_mixed/main.yml One instance plus add-ons in the same run
group_vars/ha_etcd/main.yml.example group_vars/ha_etcd/main.yml Shared etcd DCS
group_vars/ha_cluster/main.yml.example group_vars/ha_cluster/main.yml Patroni clusters + HAProxy
group_vars/{minio,silo,rustfs}_s3/main.yml.example matching live file S3-compatible store deployment
group_vars/addon_<type>_single/main.yml.example matching live file One standalone add-on type (1 host)
group_vars/addon_<type>_cluster/main.yml.example matching live file One multi-host add-on cluster (3–4 hosts)
group_vars/rootless/main.yml.example group_vars/rootless/main.yml Non-root deployment account for hosts in [rootless]
group_vars/rootless_ha/main.yml.example group_vars/rootless_ha/main.yml Non-root Patroni HA scenario (child of [ha_cluster])
cp ansible.cfg.example ansible.cfg
cp hosts.ini.example hosts.ini
cp group_vars/all/main.yml.example group_vars/all/main.yml
cp group_vars/single/main.yml.example group_vars/single/main.yml
cp group_vars/addon_nginx_single/main.yml.example group_vars/addon_nginx_single/main.yml
# ...and the same for every group you use

Secrets have no .example counterpart with real values. Create group_vars/<group>/secrets.yaml (or host_vars/<host>/secrets.yaml) yourself; every secrets.yaml and every live main.yml is gitignored.

Inventory: hosts.ini

Hosts are defined once in [all] with their connection variables. Every other group selects them by bare name, and --limit <group> chooses the scenario:

[all]
db-01 ansible_host=192.0.2.10 private_ip=192.0.2.10
db-02 ansible_host=192.0.2.11 private_ip=192.0.2.11
db-03 ansible_host=192.0.2.12 private_ip=192.0.2.12
db-04 ansible_host=192.0.2.13 private_ip=192.0.2.13

[all:vars]
ansible_user=root
ansible_port=22

[single]
db-01

[crosshost]
db-01
db-02

[single:vars]
ansible_group_priority=20
[crosshost:vars]
ansible_group_priority=20

[addon_pgbouncer_single]
db-01

[addon_etcd_cluster]
db-01
db-02
db-03
  • Enable one mode group at a time; each mode owns its own pgcli_instances list. The mode groups carry ansible_group_priority=20 so their variables win over the all defaults.
  • Order matters. The instance play runs with serial: 1; list the primary before hosts that create replicas from it. Add-on groups use the same rule: the first host bootstraps a quorum.
  • Set private_ip for node-to-node traffic (replication, etcd, backup SSH). ansible_host remains the SSH address; on public clouds it is often the EIP.
  • The S3 section activates exactly one store-type child under [s3] (minio_s3, silo_s3 or rustfs_s3).
  • [ha_etcd] and [ha_cluster] are role marker groups. The first etcd host bootstraps the DCS; Patroni member names follow [ha_cluster] order.
  • Add-on groups are named addon_<type>_single (one host) and addon_<type>_cluster (three or four hosts). Declare them all at once — their variables are uniquely named and --limit picks one group per run.

Rootless deployment

By default every host runs pgcli and podman as root. To run them as an unprivileged account, add the host to [rootless] and enable it in group_vars/rootless/main.yml:

[rootless]
db-01
# group_vars/rootless/main.yml
pgcli_deploy_rootless: true
pgcli_deploy_user: pgcli

ansible_user in hosts.ini is only the SSH connection account and must have sudo. pgcli_deploy_user is the account that owns pgcli’s state and runs rootless podman; the two may be different accounts. It is created automatically when missing, with a nologin shell, locked password, subordinate UID/GID ranges and systemd lingering. Packages, the podman launcher and host preparation (uidmap, /etc/containers/policy.json, userns, SELinux) still run through become as the SSH account. The pg binary stays in /usr/local/bin/pg.

Rootless containers use host networking. Binding ports below net.ipv4.ip_unprivileged_port_start (1024 by default) would fail, so the play persists net.ipv4.ip_unprivileged_port_start=0 in /etc/sysctl.d/99-pgcli-rootless.conf and writes /etc/sudoers.d/pgcli-deploy granting the deployment account exactly one command: sysctl -w net.ipv4.ip_unprivileged_port_start=0. It gets no other sudo rights. When the account already has passwordless sudo (sudo -n true succeeds as that account), the rule is redundant and the file is skipped.

Config, image cache, data and backups move under the account’s home:

Rootful (default) Rootless
/root/.pgcli/pg.yaml ~/.pgcli/pg.yaml
/var/cache/pgcli/images ~/.cache/pgcli/images
/data/pg ~/pg/data
/mnt/backup/pg ~/pg/backup

Hosts outside [rootless] keep the rootful layout. Rootless autostart uses systemd user units; the play enables lingering so they start at boot. Run with --limit rootless to deploy only those hosts. Rootless podman keeps its own per-user image store, so images are not shared with the rootful store on the same host.

For a non-root Patroni deployment, add a [rootless_ha] group and make it a child of [ha_cluster] ([ha_cluster:children] in hosts.ini). The child group inherits the HA settings from group_vars/ha_cluster and group_vars/rootless_ha/main.yml overrides the namespace, cluster and HAProxy lists with a single home-based cluster. Enable the co-located etcd DCS on the same hosts in [ha_etcd] with state: present, then run apply.yaml --limit rootless_ha. etcd, the Patroni members, the S3 backup setup and HAProxy all run as the deployment account. Keep the scenario’s pgBackRest repository under its own pgcli_backup_s3_path when the bucket is shared with another cluster.

Choose the group by business type

Each business scenario has its own inventory group and its own group_vars file. Enable one scenario group at a time; keep the unused groups declared but empty so the play patterns still resolve.

Business type Inventory group group_vars file Run
Standalone instance, no replicas [single] group_vars/single/main.yml apply.yaml --limit single
Primary + same-host replica [samehost] group_vars/samehost/main.yml apply.yaml --limit samehost
Primary + cross-host replica [crosshost] group_vars/crosshost/main.yml apply.yaml --limit crosshost
Standalone instance + add-ons [instance_addon_mixed] group_vars/instance_addon_mixed/main.yml apply.yaml --limit instance_addon_mixed
Machine fleet monitoring + alerting [observable] (or a custom group with its own copy of the example) group_vars/observable/main.yml apply.yaml --limit observable
Patroni HA cluster [ha_etcd] + [ha_cluster] group_vars/ha_etcd/main.yml + group_vars/ha_cluster/main.yml apply.yaml --tags addon,ha
Rootless Patroni HA cluster [rootless_ha] (child of [ha_cluster]) + [ha_etcd] group_vars/rootless_ha/main.yml + group_vars/ha_etcd/main.yml apply.yaml --limit rootless_ha
S3-compatible backup store one of [minio_s3] / [silo_s3] / [rustfs_s3] under [s3] matching group_vars/<type>_s3/main.yml deploy-s3.yaml
Standalone add-on (one type) [addon_<type>_single] group_vars/addon_<type>_single/main.yml apply.yaml --limit addon_<type>_single --tags addon
Multi-host add-on cluster [addon_<type>_cluster] group_vars/addon_<type>_cluster/main.yml apply.yaml --limit addon_<type>_cluster --tags addon

The four scenario groups (single, samehost, crosshost, instance_addon_mixed) are mutually exclusive deployment modes: their hosts often overlap, and each enabled group supplies its own pgcli_instances list, so enabling two at once can mix them. HA and S3 are supporting deployments with their own groups and play selection; when a host is part of an HA cluster, do not also list it in an active scenario group.

For a normal deployment, declare the instances and add-ons together in the scenario group’s file and run apply.yaml --limit <scenario>. The addon_<type>_<mode> groups are for isolated add-on testing: their variable files are not merged into a scenario group automatically, so copy the entries (and their params) into the scenario group when you want them there.

Add-on groups can all stay declared at once because every variable is uniquely named and --limit selects one group. Keep the scenario and HA groups disabled while running add-on groups — their group-level pgcli_instances and pgcli_addons override the list selected by the add-on --limit.

Global variables: group_vars/all/main.yml

The example file is commented field by field. The blocks that matter most:

Variable Meaning
pgcli_install_version Release tag to install; empty means latest
pgcli_install_force Re-run the installer even when pg exists
pgcli_install_binary_url, pgcli_images_http_url, pgcli_download_mirror Offline/air-gapped install source (the last covers juicefs/zerofs/duckdb binaries and DocumentDB DEBs); see Offline and air-gapped installs
pgcli_sqlite_install Run pg sqlite install during the install play (sqlite3 plus the pinned Litestream; not an add-on type)
pgcli_install_path Binary path, default /usr/local/bin/pg
pgcli_deploy_rootless, pgcli_deploy_user Non-root deployment for [rootless] hosts (see Rootless deployment); defaults stay in all
pgcli_namespace_path Host-default namespace directory; empty uses <deployment home>/.pgcli/pg.yaml (/root rootful, the account’s home rootless)
pgcli_namespaces Named namespace → pg.yaml directory map
pgcli_config_defaults pg config init values: namespace, base_dir, backup_dir, port ranges
pgcli_config_overrides Per-group namespace override (set by each mode example)
pgcli_instance_defaults Default state, autostart, backup_target, password_length, extensions, clean_data
pgcli_instances Desired instances (normally set per mode group; add-on groups declare their own, selected by --limit)
pgcli_daemons Host processes managed by pg daemon (webhook receivers, …); entries without host run everywhere
pgcli_addons The selected add-on group’s list (addon_<kind>_addons)
_addon_limit, _addon_group, _addon_type, _addon_mode Add-on selector derived from --limit addon_<type>_<single|cluster>

pgcli_config_defaults is consumed only on the first pg config init; editing it later does not rewrite an existing pg.yaml.

First run

cd ansible
uv run ansible-inventory --graph   # validates hosts.ini and prints the groups
uv run ansible-playbook playbooks/ping.yaml
uv run ansible-playbook playbooks/apply.yaml --limit single

The full play directory (and what each tag runs) is on the Playbooks page.

Tips

The repository tracks only the *.example files; live main.yml, hosts.ini, ansible.cfg, secrets.yaml and var/ are gitignored. If you maintain your own Ansible project (for example a fork you commit to), keep passwords, S3 secret keys and certificates in a separate secrets.yaml rather than inline in main.yml. Both group_vars/<group>/secrets.yaml and host_vars/<host>/secrets.yaml are loaded automatically, so the variables resolve the same way while the secret file stays out of version control (the repository’s .gitignore already covers this layout).

3 - Offline and air-gapped installs

Serve container images, the pg binary, the podman launcher and runtime downloads (host binaries and DEBs) from a LAN HTTP server

The playbooks can install and operate pgcli without reaching GitHub, ghcr.io, Docker Hub or distro mirrors. A single static HTTP directory on the LAN can serve every artifact: consumers always fetch <base>/<basename>, so one flat server root is enough.

What the server hosts

Variable Artifact Consumed by
pgcli_images_http_url podman save tarballs produced by make container-images-export pgcli role during install; pg_addon / pg_ha_haproxy lazily
pgcli_install_binary_url pg binary — raw file or pgcli_<version>_linux_amd64.tar.gz pgcli role
pgcli_podman_binary_url podman-launcher binary pgcli role when /usr/local/bin/podman is missing
pgcli_download_mirror host binaries (juicefs, zerofs, duckdb, Litestream) and DocumentDB DEBs pg at runtime through PGCLI_DOWNLOAD_MIRROR

All four are set in group_vars/all/main.yml; the committed template is group_vars/all/main.yml.example.

Changing the variables

The live file is gitignored. Copy the template on first use, then edit it in place:

cp group_vars/all/main.yml.example group_vars/all/main.yml
$EDITOR group_vars/all/main.yml

Point every family at the same server root, and leave a variable empty to keep the online path for that artifact:

pgcli_install_binary_url: "http://192.0.2.10:18080/pg"
pgcli_podman_binary_url: "http://192.0.2.10:18080/podman-launcher-linux_amd64"
pgcli_download_mirror: "http://192.0.2.10:18080"
pgcli_images_http_url: "http://192.0.2.10:18080"

Variable precedence is host_vars/<host>.yml > group_vars/<group>/main.yml > group_vars/all/main.yml. Override only the hosts or groups that differ instead of editing all when both online and offline hosts are managed from the same inventory. pgcli_images is a complete replacement list, not a merge, so a scenario group that defines its own list overrides the one in all.

Edits take effect on the next playbook run. The binary is only reinstalled when pg is missing or pgcli_install_force: true; image tarballs are only fetched when the tag is absent from the local podman store (or pgcli_images_force_load: true).

On an air-gapped control node, point pgcli_install_script_src at a local checkout instead of the GitHub raw URL:

pgcli_install_script_src: "{{ inventory_dir | dirname }}/scripts/install.sh"

The role then copies the script to the target host; only an http(s):// value is downloaded on the host.

Egress proxy

When hosts reach the internet only through a forward proxy (for example a Privoxy add-on on a connected machine), set the global pgcli_proxy_url instead of — or alongside — the LAN mirror. Proxy startup, the full variable set, NO_PROXY rules, manual SSH usage and verification are covered in Egress proxy.

Starting the server with pg http

To export every image and wire the server up to Ansible step by step, see Offline image server. The rest of this page places that server in the context of all offline artifacts.

pg http is pgcli’s built-in static file server. It runs as a detached host process (no container) and supports HEAD/Range requests, which the image loader and its pre-checks rely on.

# On a host with podman and a repository checkout: export the tarballs.
make container-images-export          # writes images/*.tar, skips existing files

# Serve that directory. The default is 127.0.0.1:18080.
pg http start --listen 0.0.0.0 --port 18080 --dir images

pg http status
pg http stop http-18080
  • If the requested port is busy, the next free port is used (up to 100 attempts). Check pg http status and keep the URLs in group_vars/all consistent with the port actually bound.
  • The server is detached and survives the terminal that started it. It does not start at boot unless enabled: pg autostart enable --http --name http-18080.
  • There is no authentication. Keep the listener on a trusted network. --tls encrypts traffic but does not authenticate clients.
  • Files must sit directly in the served directory: every consumer requests <base>/<basename>, with no path prefix.

Container images

make container-images-export exports every image in the Makefile IMAGES list as images/<repo>_<tag>.tar (: becomes _; the export pins linux/amd64). The manifest in group_vars/all/main.yml must use exactly those archive names:

pgcli_images:
  - image: ghcr.io/mars-base/pgcli/pgcli-pg:18-2.59.3
    archive: pgcli-pg_18-2.59.3.tar
  - image: ghcr.io/mars-base/pgcli/pgcli-backup:2.59.3
    archive: pgcli-backup_2.59.3.tar
  - image: docker.io/edoburu/pgbouncer:v1.25.2-p0
    archive: pgbouncer_v1.25.2-p0.tar
    auto_load: true
    addons: [pgbouncer]

How the list is consumed:

  • Entries without auto_load are core images. The install play loads them into podman’s local store after checking that each archive is present.
  • auto_load: true with addons: [type] marks add-on images. They are loaded on demand by the pg_addon role when an add-on of a matching type is first created (- in the type name becomes _). pg_ha_haproxy uses the same mechanism for HAProxy.
  • Setting pgcli_images_http_url makes scripts/install.sh run with --skip-pull; no image is pulled from a registry.
  • Before changing anything, the install play sends HEAD requests to the server root and to every core archive, and aborts with the offending names if any is unreachable. Lazy add-on archives are fetched when first needed.

Trim the list to the images a scenario actually uses: the first run on a host with an empty store transfers only the listed core archives. Keep pgcli-pg and pgcli-backup; add one entry per add-on type in use (remove auto_load to preload it during install instead of on first use).

Transferred tarballs are cached on the target host. The cache is kept across runs — only missing images are transferred again — and is safe to delete:

Layout Cache directory
rootful /var/cache/pgcli/images
rootless ~/.cache/pgcli/images under the deployment account

Rootless podman uses a separate image store owned by the deployment account. Images already loaded as root are not visible there, so the rootless install loads its own copy from the offline server.

The pg binary and the podman launcher

pgcli_install_binary_url accepts either a raw pg binary or a release tarball named pgcli_<version>_linux_amd64.tar.gz. A tarball is extracted and its top-level pg member is installed to pgcli_install_path (/usr/local/bin/pg by default); a raw file is copied as-is. In both cases scripts/install.sh still runs with --skip-binary, so host initialization (uidmap, /etc/containers/policy.json, user namespaces, SELinux) is not skipped.

pgcli_podman_binary_url installs the podman-launcher binary as /usr/local/bin/podman when no podman exists on the host. The launcher fetches its static podman tree on first use, so a fully air-gapped host still needs podman pre-installed (distribution package or a pre-seeded launcher state) before the first podman invocation succeeds.

Runtime downloads: host binaries and DEBs

Some add-ons download assets when they are created, after installation is already complete. pgcli_download_mirror redirects those downloads: the playbooks export it as PGCLI_DOWNLOAD_MIRROR to every pg command, and pgcli rewrites any http(s) asset URL to <mirror>/<basename>. URLs already under the mirror and non-HTTP paths are left untouched.

Place the upstream assets under their original file names:

Consumer Asset basename
pg addon install juicefs juicefs-1.4.1-linux-amd64.tar.gz / juicefs-1.4.1-linux-arm64.tar.gz
pg addon install zerofs zerofs-pgo-multiplatform.tar.gz
pg addon install duckdb duckdb_cli-linux-amd64.zip (1.x, default 1.5.6) or duckdb-cli-linux-amd64.tar.gz (2.x, pinned 2.0.0); amd64 only
pg sqlite install (Litestream) litestream-0.5.17-linux-x86_64.tar.gz (amd64) / litestream-0.5.17-linux-arm64.tar.gz
pg extension install documentdb ubuntu24.04-postgresql-18-documentdb_1.0-0_<arch>.deb and libicu74_74.2-1ubuntu3.1_<arch>.deb

Behavior and caveats:

  • pgcli still verifies pinned SHA-256 digests after downloading, so mirrored files must be byte-identical to the upstream release assets.
  • Use pinned versions. --version latest queries the GitHub API, which is not redirected by the mirror.
  • The DocumentDB DEBs are copied into the derived extension image and installed there; the mirror covers exactly these two packages.
  • Other catalog extensions are built from the Pigsty DEB repository inside podman build, which pgcli_download_mirror does not redirect. With pgcli_proxy_url set, the build’s apt and curl use that proxy; on a fully air-gapped network, pre-build the derived -ext image on a connected host (or mirror the Pigsty repository and point apt at it on the build host) and distribute the image through pgcli_images.
  • Litestream is not an add-on: pg sqlite install provisions sqlite3 and the pinned Litestream binary. Set pgcli_sqlite_install: true on the hosts or groups that use SQLite and the pgcli role runs it during the install play, with the same mirror redirect. sqlite3 itself comes from the distribution package manager, so air-gapped hosts need that package preinstalled (or a local distro mirror).
  • Outside Ansible, export PGCLI_DOWNLOAD_MIRROR yourself before running manual pg addon install / pg extension install / pg sqlite install commands.

Reference file list

The current LAN server is a complete mirror of the default pgcli_images manifest (44 image tarballs) plus the install binaries and every runtime asset at the versions pgcli pins. Use it as the authoritative checklist when building a new server; regenerate the image names with make container-images-export whenever image tags change.

Each line is <sha256> <filename> (sha256sum format), so a downloaded directory can be verified with sha256sum -c.

# Container images (podman save, docker-archive)
57afcb88cc34c24516b32714599c523cae5e4c92e736467062829833e585257d  alertmanager_v0.34.1.tar
a14e80bef8be07614c0291ce2355ad8d894319c2a6f0cf4c4f1beaa6cf522b44  beegfs-meta_8.4.0.tar
4b4f84fbb63325c91145569562bfd611f8d99f663eb9d1eac2b7ca4a60df310e  beegfs-mgmtd_8.4.0.tar
bee066403b9f0c993d0771ef6a1b043a0dd3493042eec8c4bad283d3de34ff90  beegfs-storage_8.4.0.tar
93d7058def24e8433289f81d7618dd5db6ed1615e1d636f1cc62cc065b7e078d  clickhouse-server_26.8.36.3.tar
3b656d42cdbefb81818dcdd14f72a1c6399d15e3d6a3ea9630fd1b28929b7275  etcd_v3.5.30.tar
5e48fd56e8e09ba45ea65f7a2756329b17031ff9c714ee63b447b3a850ab6e19  garage_v2.4.1.tar
bdbdd7f0c98ebf27f200eb700ed843af342b3cb0fb2160fda1fc501750f2f214  gitea_28.1.0.tar
bdbaf2766541a181981ca09e4303591e27cbc48a40df1b14e4e6e399bba72616  grafana_13.2.4.tar
26d7b2146246600e91acaf82c90cb617cc03f2bfb326931f34da9e498b2e67e0  haproxy_3.2.23-alpine.tar
1227f164fdfd18f0394faa3f0661a01268987e4d83dbd5788e946388cdee4fa4  kafka_4.4.0.tar
0a793f19e64e7f83256bc3f6bf7bdf91e57fd01a1c7a9a3bc6eaea67786116df  nginx_1.27-alpine.tar
36f9aa3df9b4dbb92c04224c642a614c71757a6a51eb9b8b7fdf4336774458e2  node-exporter_v1.12.1.tar
f36fd9dc6da057b14b51c7a913349e8951aed6ab2c14bd786098e3fb851369fd  pgadmin4_9.18.tar
3110efd6d12a2542f1f033367fd00289b86aaf2150ccd8ada8737e846df0ca28  pgbouncer_v1.25.2-p0.tar
c12395bb1c9ea0b8095fbc8ff3806958de28ee44d418247490340a8e74fcfc98  pgcli-backup_2.59.3.tar
2b15818c746bbbce40da49bfff111c69663c822941b2a7f1cbcfec9f267420a1  pgcli-documentdb-gateway_1.0.0.tar
03d80d54bfa21bce01827ae557547f15584f6b906762a21a2d196cddcfe05f94  pgcli-influx2tsdb_1.3.2.tar
a227354e55153e1ad470e05e95000aa177395d8007a9a70a3e8513ff0173bc6e  pgcli-influxdb_1.13.1.tar
d1cd9b9447132d8728211fb5e05830e9c6d536dfe8db7a8eb094e1cdcbb567bb  pgcli-mc_20250813083541.tar
412b8ac7decfebb977ba85b77aaf35d0fe95da63de71f2e10e8639e31c97d96c  pgcli-minio_20250422221226.tar
9179e64e34c72db01dae3748ff4118a93796a9c0bba0826e49d70b6b8720d10a  pgcli-mongosh_2.14.1.tar
0519713fdf5510b72e3bd2b5f69ab4ef73695eeb3d5f6a822383da62754542b0  pgcli-patroni_18-4.1.5.tar
46bbe0a99d342c967097c4147fa0ebd1ce8f6c0128676080f11efeb1be21f831  pgcli-pg_18-2.59.3.tar
377877a78d2fc29a02ed4658946d2f248f909a524bb4fc091bb3d4acdb70d413  pgcli-privoxy_4.2.0.tar
e13cc780306750ad6dd6d543d41249fb8e62dfff01c956a16d2a4f093d49a6b8  pgcli-rustfs_1.0.0.tar
5ab1ad708255e084d60cabbb7dbe807ea1c26dd767ef86502732f5f1132ebca2  pgdog_v0.1.57.tar
529231f4bfc8ea0240ec753a36aea676970ac39606529e219b751d03648926ff  pg_exporter_1.5.0.tar
5cbbce30d39c3640dc64052f220aa3d825f3218f36ef5083a0351a3db9db9989  postgrest_v16.3.tar
e8a81d28d62dd12b2cdf1a75f04cd3107f222d049d89d268e2e887fc2c112bed  predixy_7.0.1-alpine.tar
b4efb1483945d650e09d2c8e3b1970f9acee02d42c5d75517b8e2b2be4812131  prometheus_v3.15.0.tar
857d511abc27aef7103d64af4c2fa9b1425ab45f30f5d1198532f0db166cfaed  rabbitmq_4.4.0-management.tar
1b8591ac18ab53e3cc249357682e0c66c07375e1c58fd8781fa3315946ee8119  redis_7.4.11.tar
27cf00f651008c6c317ab4eb18a5b5e3415b3a5c376b8f723d8ab644dda3cba1  redis_8.10.2.tar
cb595d76e5d748f39715a1a4b76db1eba9fb26ed38c597d9b9b21e193491e1b0  rocketmq_5.5.0.tar
f3744934bd7b2c7b09d0194968c39b44469fd131ffbd6a291f36db009dba773b  seaweedfs_4.48_large_disk.tar
82e865abbc16a57b44b2e78bd70b31b311e6130542ddfdc49cc382c835522985  silo_RELEASE.2026-09-16T00-00-00Z.tar
4cc9904054ac3387538b1d152f51a2ecc78d4f25ff030a940eacfe8c23fcf0c4  victoria-logs_v1.53.0.tar
f39023521577ea6d0ca335de42cd016327a4bd63fbceccdfa58a080324671406  victoria-metrics_v1.154.1.tar
e8dd5799352cea82bdb326448bf2ab6748d3a3d28ca9e5ea3ae47a86f444c9d7  vlagent_v1.53.0.tar
942804cc5bed04499803ec5dcba6933734fec480963c308a64364de6becf30bb  vmalert_v1.133.0.tar
3cf4053637bd7a01e378a54ac08a4a5496cbeaf37b143aaf43f6b32ff97c0374  vminsert_v1.154.1-cluster.tar
934bd154d33533752cce8078106a30cee408e688bca7b3d552bf0efdcb8dbf32  vmselect_v1.154.1-cluster.tar
3d4705f25e9fa100e2acc60a098b180c777bfc1654757dd5025ee655253bfede  vmstorage_v1.154.1-cluster.tar

# Install binaries
262a992266b0b7f18d2e2dbf043d7fb3ebfffab702bae0bfd4c769d9a50deb51  pg
689c841cb5e9f86dec84b095b7cc2581b2af51e7ee3bb3e8067b92487b312b1d  podman-launcher-linux_amd64

# Runtime mirror assets
c6507206baf7793c6013dbd82368469a45f20dc0e17a6f92f204602f652ed2bc  duckdb-cli-linux-amd64.tar.gz
6e89deac1ebbc36eed0291caf8b567b030c7b86ac35998f71854e22b3c5d5e2f  duckdb_cli-linux-amd64.zip
01ee09a21a9351a465e09906f113845e1c6a19bea70f530e5e2b2125b2dd3b82  juicefs-1.4.1-linux-amd64.tar.gz
1015ade83a7a93180a29f6c93ee5780a3eda52522331934ef2ef0cc0921995fd  juicefs-1.4.1-linux-arm64.tar.gz
c9a70989678660eed9a1e904c74fa043da8bec8e2036856fc16e31ced79b04f8  libicu74_74.2-1ubuntu3.1_amd64.deb
48f93acf50dcf237a8d58ce366730a28438ce52d3f06d7a2a88b51261dd791f7  libicu74_74.2-1ubuntu3.1_arm64.deb
f8ca4a050095c1efbda2c4365172e61bf9d955ea0d9ac42f448b52e51819baa5  litestream-0.5.17-linux-arm64.tar.gz
cfb371176d164437ae869f8351cfde49bd1804ae71c61923f75c9cba9c9c006d  litestream-0.5.17-linux-x86_64.tar.gz
cc26f8225af13233f901f86292d5a8373276654454c671316cd603d20378fdbf  ubuntu24.04-postgresql-18-documentdb_1.0-0_amd64.deb
6afc91e21b72990d1d43421b79e4484d7cd55366c1d0436fa71f4cc2f119d6eb  ubuntu24.04-postgresql-18-documentdb_1.0-0_arm64.deb
367b2e79e05167af8409b28322f21b1ae5de033fc40820a3c27684a9974a56f2  zerofs-pgo-multiplatform.tar.gz

The runtime assets cover every create-time download through pgcli_download_mirror, at the versions pgcli pins: juicefs 1.4.1 (amd64/arm64), duckdb 1.5.6 and 2.0.0 (amd64 only), Litestream 0.5.17 (x86_64/arm64), zerofs, and the DocumentDB DEBs. Other versions fail the pinned SHA-256 check, so update the pin in pgcli before mirroring a new release.

Verifying the setup

Check one archive per family, then run a deployment:

curl -I http://192.0.2.10:18080/pgcli-pg_18-2.59.3.tar
curl -I http://192.0.2.10:18080/pg
curl -I http://192.0.2.10:18080/ubuntu24.04-postgresql-18-documentdb_1.0-0_amd64.deb

uv run ansible-playbook playbooks/apply.yaml --limit single
uv run ansible single -m command -a 'pg list'

The install play fails before making changes when the server root or a core archive is unreachable; a HEAD request returning anything other than 200 is treated as missing.

4 - Egress proxy

Route installs, downloads and extension builds through a forward proxy in an isolated data center

In an isolated data center the database hosts have no direct route to the internet. Run one Privoxy add-on on a host that does, and point the playbooks at it — installs, image pulls, runtime downloads and extension builds then share that egress.

managed hosts ── HTTP / CONNECT ──▶ Privoxy (connected host) ──▶ internet

Start the proxy

Run this on the host with internet access; the same pgcli binary and image set is enough, no extra package:

pg addon install privoxy --name egress --allow-network 10.0.0.0/8
  • Privoxy listens on 0.0.0.0:8118 by default. --allow-network is a client whitelist; with no ACL and a non-loopback listener the install prints an open-proxy warning.
  • One listener serves HTTP directly and HTTPS through CONNECT, so a single URL covers both.
  • Verify from a host that will use it:
curl -x http://192.0.2.10:8118 -o /dev/null -w '%{http_code}\n' https://repo.pigsty.io/

See Privoxy for ACL syntax, custom upstream SOCKS, autostart and logs.

Configure Ansible

Set two variables in group_vars/all/main.yml (copy it from main.yml.example if it does not exist yet):

pgcli_proxy_url: "http://192.0.2.10:8118"
pgcli_no_proxy: "localhost,127.0.0.1,::1"

pgcli_proxy_url is exported to the deployment account as HTTP_PROXY and HTTPS_PROXY (uppercase and lowercase). Leaving it empty keeps direct connections: the derived pgcli_proxy_env is then {} and every play behaves as before. Check the evaluated result with:

cd ansible
uv run ansible <host> -m debug -a 'var=pgcli_proxy_env'

What uses the proxy

Step How it reaches the proxy
Install play scripts/install.sh (apt, release download) and every get_url
Images podman pull, image loading, lazy add-on image loads
Runtime downloads pg addon install …, pg sqlite install — Go HTTP client
Extension builds podman build behind pg extension install

What does not

  • Running services: containers are created with --http-proxy=false, so PostgreSQL, backup, pgbouncer, PostgREST and Gitea never inherit the proxy.
  • Patroni and backup fallback image builds keep the proxy explicitly disabled.
  • The LAN reachability checks in offline-check.yml bypass the proxy.

NO_PROXY

The playbooks append the hosts of the four offline URLs (pgcli_install_binary_url, pgcli_podman_binary_url, pgcli_download_mirror, pgcli_images_http_url) and every inventory private_ip to pgcli_no_proxy.

Add other internal endpoints by exact IP or hostname. Python (Ansible get_url/uri) and apt do not understand CIDR entries in no_proxy; a range such as 10.0.0.0/8 only helps curl and Go clients. Running a LAN mirror and an egress proxy together is fine — the mirror hosts are added automatically.

Using it without Ansible

In an SSH shell, export the same variables before running pg:

export HTTP_PROXY=http://192.0.2.10:8118
export HTTPS_PROXY=http://192.0.2.10:8118
export NO_PROXY=localhost,127.0.0.1,::1

pg and the podman commands it runs inherit them. Three caveats:

  • sudo resets the environment by default — use sudo -E, sudo env HTTP_PROXY=... pg ..., or env_keep in sudoers.
  • The exports cover only that shell and its children; pg start --autostart and other boot-time paths do not see them.
  • Containers created by pgcli still get --http-proxy=false; the proxy is never passed into a long-running service.

Security

Prefer Privoxy client ACLs to a user:pass@ URL: credentials embedded in the proxy URL are visible in process environments (/proc/<pid>/environ) and in verbose Ansible logs. Keep the listener on the private network and the ACL whitelist narrow.

Verify the whole path

  1. From each managed host, fetch an external URL through the proxy with curl -x as shown above.

  2. Run one extension install against a test instance:

    pg extension install hll -i <instance>

    The build must reach repo.pigsty.io, apt.postgresql.org and deb.debian.org. Watch pg logs addon privoxy --name egress (logfile /dev/stdout) or capture port 8118 while it runs.

  3. Confirm the recreated container is clean:

    podman exec <container> env | grep -i proxy || echo clean

If the extension build bypasses the proxy, check that the process running pg extension install actually has the variables (Ansible sets them on the install play). Internal requests that unexpectedly hit the proxy usually mean the exact IP or hostname is missing from NO_PROXY.

5 - Offline image server

Export every container image on a connected host and serve the tarballs over HTTP for air-gapped installs driven by pgcli_images

An air-gapped install needs two things: a directory of image tarballs reachable on the LAN, and pgcli_images_http_url pointing at it. The repository ships scripts/export-images.sh for the first part: it reads the list from docs/images.md or from the Ansible pgcli_images variable, pulls each image, and saves it as a docker-archive tarball whose name matches the offline manifest. pg http provides the second part.

connected host                              isolated network
export-images.sh ──▶ /srv/offline-images ──HTTP──▶ pgcli_images_http_url
  (podman pull/save)      (pg http)               (loaded into podman)

Export the images

By default the script reads the image tables in docs/images.md and writes to images/ under the repository root:

./scripts/export-images.sh

Using the Ansible list as the source is recommended: then each tarball name comes from pgcli_images[].archive, so it cannot drift from what the playbooks consume:

# Use the live group_vars/all/main.yml when present, otherwise main.yml.example
./scripts/export-images.sh --ansible ansible/group_vars/all/main.yml -o /srv/offline-images

Both sources resolve to 44 images with the same image-to-filename mapping. Options:

Option Meaning
--manifest FILE Use another Markdown image list (mutually exclusive with --ansible)
--ansible FILE Read pgcli_images from an Ansible group_vars file and use its archive names
-o, --output DIR Output directory; default images/ in the repository
--platform ARCH Pull platform; default linux/amd64 (use linux/arm64 for ARM hosts)
-n, --dry-run Print the plan without pulling or writing anything
-f, --force Re-export tarballs that already exist

Check the plan first:

./scripts/export-images.sh --ansible ansible/group_vars/all/main.yml --dry-run

On a host that needs a proxy, the script inherits the environment and podman pull uses the same egress:

export HTTP_PROXY=http://192.0.2.10:8118
export HTTPS_PROXY=$HTTP_PROXY
./scripts/export-images.sh -o /srv/offline-images

See Egress proxy for running the proxy itself.

Naming and behaviour

  • Names follow <repository-basename>_<tag>.tar (: becomes _), for example ghcr.io/mars-base/pgcli/pgcli-pg:18-2.59.3 → pgcli-pg_18-2.59.3.tar. With --ansible, the archive field is used verbatim.
  • Existing tarballs without --force are reported as SKIP, so an interrupted run can simply be restarted.
  • Each archive is written to .tmp and atomically renamed on success; a failure never leaves a partial file. One failed image does not stop the rest; the script exits non-zero and lists the failures at the end.
  • Images are pulled with --platform before saving because podman save cannot write a multi-arch manifest list to docker-archive.
  • The 44 tarballs total several GB; make sure the output filesystem has room.

Start the HTTP server

pg http is pgcli’s built-in static file server. It runs as a detached host process (no container) and supports HEAD/Range requests, which image pre-checks and loading rely on.

# Serve the export directory; the default listener is 127.0.0.1:18080
pg http start --name images --listen 0.0.0.0 --port 18080 --dir /srv/offline-images

# Confirm the actual address and port (it moves to the next free port if busy)
pg http status

To maintain the store from a browser, add the write-mode flags:

pg http start --name images --listen 0.0.0.0 --port 18080 \
  --dir /srv/offline-images --allow-upload --allow-dir --allow-delete \
  --admin-ip 192.0.2.20,192.0.2.21

The listing then offers an upload form, a “new folder” form and per-file delete buttons, so tarballs can be replaced or added without a shell. Uploads are capped at 1 GiB per request by default; raise it with --max-upload if the tarballs are larger. --admin-ip restricts the write controls to the listed source addresses: everyone else sees the plain read-only listing and gets 403 on writes. These modes come with no authentication either — see HTTP file server.

Add --auth (or --auth-env) to put the whole site behind HTTP Basic Auth — listings, downloads and writes:

pg http start --name images --listen 0.0.0.0 --port 18080 \
  --dir /srv/offline-images --allow-upload --allow-dir --allow-delete \
  --auth images:<password> --auth-env PGCLI_HTTP_AUTH

Accounts can also live in an htpasswd file: pg http htpasswd images --file /srv/offline-images.htpasswd, then start with --auth-file /srv/offline-images.htpasswd.

Note that the bundled Ansible tasks (ansible.builtin.uri for the HEAD pre-check, ansible.builtin.get_url for downloads) do not send credentials. If you enable Basic Auth on the image server, pass url_username / url_password in your own overrides of those tasks, or keep this particular server unauthenticated on a trusted network.

Enable it at boot if needed:

pg autostart enable --http --name images

The server can also be managed entirely from Ansible: see HTTP file server. playbooks/deploy-http.yaml reconciles every pg http parameter from group_vars/http/main.yml (directory, write modes, TLS, auth), syncs the pg and podman binaries, and registers the autostart command above.

Caveats:

  • There is no authentication unless you add --auth. Use 0.0.0.0 only on a trusted network or behind a firewall. --tls encrypts traffic but does not authenticate clients, and its self-signed certificate must be trusted by the clients. Combine --auth with --tls when the server leaves the host.
  • If the port is busy, pg http tries the next free one (up to 100 attempts). Always check pg http status and keep pgcli_images_http_url consistent with the port actually bound.
  • Files must sit directly in the served directory: consumers request <base>/<basename> with no path prefix.

Configure Ansible

Point the cluster at the server root in group_vars/all/main.yml:

pgcli_images_http_url: "http://192.0.2.10:18080"

With it set, scripts/install.sh runs with --skip-pull and the install phase never contacts a registry. Two requirements follow:

  1. Every archive in pgcli_images must match a filename on the server exactly. Exporting with --ansible guarantees this.
  2. All core images (entries without auto_load) must be present. Before changing anything, the install play sends HEAD requests to the server root and to every core archive; any miss aborts with the specific filename.

Images marked auto_load: true are fetched on demand: the first time an add-on of that type is created. You can therefore export only the add-on images you actually use. Manifest trimming and lazy loading are covered in Offline and air-gapped installs.

If pgcli_proxy_url is set as well, the image server hostname is added to NO_PROXY automatically, so LAN downloads never go through the proxy.

Verify

On one target host in the isolated network:

# The server answers with 200 and a Content-Length
curl -I http://192.0.2.10:18080/pgcli-pg_18-2.59.3.tar

# Run the playbook
cd ansible
uv run ansible-playbook playbooks/apply.yaml

The first host should report loading the core images from pgcli_images_http_url rather than pulling from a registry. When an add-on is created for the first time, confirm that its tarball is downloaded on demand.

Updating images

When tags change, re-export from the new pgcli_images list; filenames change with them, and old tarballs are not deleted automatically:

./scripts/export-images.sh --ansible ansible/group_vars/all/main.yml -o /srv/offline-images

Existing files are skipped; add --force when a tarball must be pulled again. The directory is flat, so removing stale tarballs that the manifest no longer references does not affect images already in use.

6 - HTTP File Server

Manage pg http file servers declaratively with the pg_http role and deploy-http.yaml: directories, write modes, TLS, Basic Auth, autostart, and offline binary distribution

playbooks/deploy-http.yaml brings pg http file servers under Ansible management. pg http is a host process (no container, no add-on type), so this uses a standalone pg_http role and a standalone playbook instead of pg_addon / apply.yaml, mirroring how deploy-s3.yaml is organized.

The role reconciles each server declared in pgcli_http_servers: it compares the running spec by name and runs pg http stop + pg http start when anything differs, creates the served directory, optionally copies the offline binaries into it (sync_binaries: true), and registers boot autostart as needed. Binary copying is disabled by default. Re-running converges to the declared state.

Configuration

Prepare an [http] group in the inventory (hosts.ini, gitignored), for example:

[http]
node-http ansible_host=192.0.2.11 ansible_user=root

The server list lives in group_vars/http/main.yml (gitignored; copy it from the .example file next to it). Every field is optional; defaults are shown in parentheses:

Field pg http flag Description
name --name (required) Server name, also the state file name
host — Reconcile only on this inventory host; omitted means all target hosts
state — started (default) / stopped / absent
autostart — Register boot autostart (default true; only allowed with state: started)
dir --dir Served directory (default /srv/offline-images)
dir_owner — Directory owner (default deployment account); applies to the directory only
dir_group — Directory group (default deployment account); applies to the directory only
dir_mode — Directory permissions (default 0755); applies to the directory only
listen --listen Listen address (default 127.0.0.1)
port --port Listen port (default 18080)
allow_upload --allow-upload Upload form (default false)
allow_dir --allow-dir Create-directory form (default false)
allow_delete --allow-delete Per-file delete button (default false)
max_upload --max-upload Per-upload limit (default 1G, e.g. 512M)
admin_ips --admin-ip Source-address allowlist for write modes (list, joined with commas)
tls --tls HTTPS with a self-signed certificate generated and renewed under the pgcli base dir
tls_cert --tls-cert PEM certificate path on the target host; implies TLS
tls_key --tls-key Private key path paired with tls_cert
auth --auth Basic Auth entries, each USER:PASSWORD (list)
auth_env --auth-env Names of controller environment variables holding USER:PASSWORD
auth_file --auth-file htpasswd files on the target host (bcrypt entries)
force — Restart even when the spec matches (default false)
sync_binaries — Copy the offline binaries into dir (default false)

Examples

A directory writable by a scheduled job running as http-writer:

pgcli_http_servers:
  - name: review
    dir: /data/www/lh3-review
    dir_owner: http-writer
    dir_group: http-writer
    dir_mode: '0755'
    listen: 0.0.0.0
    port: 11235

Minimal: expose the offline directory over HTTP on the LAN and register boot autostart.

pgcli_http_servers:
  - name: images
    dir: /srv/offline-images
    listen: 0.0.0.0
    port: 18080
    autostart: true

Write modes restricted to specific sources, with a larger upload limit:

  - name: share
    dir: /srv/share
    listen: 0.0.0.0
    port: 18081
    allow_upload: true
    allow_dir: true
    allow_delete: true
    max_upload: 512M
    admin_ips:
      - 192.0.2.20
      - 192.0.2.21

TLS, two ways (tls: true uses the auto-generated self-signed certificate; certificate and key paths refer to the target host):

  - name: images
    tls: true
  - name: files
    tls_cert: /etc/pgcli-http/files.crt
    tls_key: /etc/pgcli-http/files.key

The three Basic Auth sources can be combined, but a username may appear in only one of them:

  - name: images
    auth:
      - "alice:s3cret"          # plaintext in the gitignored group_vars
    auth_env:
      - PGCLI_HTTP_AUTH         # controller env var, value like bob:hunter2
    auth_file:
      - /home/pgcli/pg/data/http/htpasswd

auth_env values are read on the controller with lookup('env', ...); only the variable names are passed to the target host as --auth-env. When plaintext auth or auth_env entries are present the start task runs with no_log, so passwords do not appear in the default output or the recap.

Maintain htpasswd files with pgcli itself (incremental upsert, other accounts preserved):

printf '%s\n' "$PASSWORD" | pg http htpasswd alice
# Writes to <base_dir>/http/htpasswd by default; --file overrides the path

Binary sync

Binary copying is disabled by default. Set sync_binaries: true on a server to refresh the controller’s bin/pg into images/pg, then copy only pgcli_http_binaries (default pg and podman-launcher-linux_amd64) into its dir. Image tarballs are not copied here; export them into that directory first with scripts/export-images.sh (see Offline image server).

The controller therefore needs a make build first, and the other binaries must already exist under images/ when binary copying is enabled; otherwise the playbook fails before any host is modified. Override the variables in group_vars/http/main.yml:

pgcli_http_binaries: [pg, podman-launcher-linux_amd64]
pgcli_http_default_dir: /srv/offline-images

A file-server host runs no containers, so the install stage skips container images by default: the offline image server is not checked, no images are loaded, and the installer runs with --skip-pull. That avoids a large transfer on a distribution host that has no pg binary yet and needs no local images. If the host must also carry images for other containers, override with -e pgcli_load_images=true -e pgcli_install_skip_pull=false.

Running

cd ansible

# Install/update pgcli and reconcile the servers on the [http] group
uv run ansible-playbook playbooks/deploy-http.yaml --limit http

# A specific host
uv run ansible-playbook playbooks/deploy-http.yaml -e HOSTS=node-http

# Reconcile only (skip the install role)
uv run ansible-playbook playbooks/deploy-http.yaml --limit http --skip-tags pgcli

The playbook has two stages: the pgcli tag installs and configures the host, the http tag only reconciles servers. Servers run as the deployment account (pgcli in rootless setups); served directories under /srv are created by root and chowned to that account.

Idempotency and lifecycle

  • Spec comparison covers dir, listen, port, the three write-mode flags, max_upload, admin_ips, TLS, the certificate/key paths, and the auth usernames with their passwords/hashes. Any change restarts the server.
  • The role runs pg http stop first so stale state files are cleaned up and pg http start cannot create an images-2 style duplicate.
  • When the port is taken, pg http silently increments it; the role re-reads the state file after starting and fails if the bound port differs from the declared one, so consumers never get a wrong URL.
  • The health probe hits http(s)://<listen>:<port>/__pgcli_health (skipping certificate validation under TLS); the endpoint needs no authentication.
  • With autostart: true the role snapshots the running spec into pg.yaml via pg autostart enable --http --name, refreshing it on every restart. state: stopped or autostart: false removes the snapshot.
  • state: absent stops the server and deletes the state file.

Caveats

  • Auth is compared by username and password: adding or removing accounts, and changing the password of an existing one, restarts the server. Inline auth and auth_env passwords are verified on the controller against the bcrypt hashes in the running spec; auth_file entries are compared hash-for-hash, so accounts edited on the target with pg http htpasswd or htpasswd -B are picked up on the next run. A running process caches the hashes it read at start-up, which is why the role stops and starts it on a difference.
  • auth_file is read only at start-up: a manual edit takes effect after the next playbook run (or an explicit force: true restart).
  • A server started by hand with pg http start is adopted: it is left alone when the spec matches, and restarted with the declared flags when it does not (manual flags missing from the configuration are lost).
  • Without auth the site is open to everyone; use 0.0.0.0 only on trusted networks, combined with admin_ips or a firewall. --tls encrypts traffic but does not authenticate clients.
  • During the install stage one “initialize the host” task always reports changed (existing install-script behavior); the reconcile stage should be changed=0 when the state matches.

7 - Playbooks

How to run apply.yaml, ping.yaml, resources.yaml, deploy-s3.yaml, ha-status.yaml and passwords.yaml — play order, tags, limits, idempotency and lifecycle orders

All commands run from the ansible/ directory through the pinned uv environment. Without --limit, apply.yaml targets every host in the inventory; in practice you select a deployment-mode group or one add-on group with --limit addon_<type>_<single|cluster>.

cd ansible
uv run ansible-playbook playbooks/apply.yaml

ping.yaml

SSH and Python connectivity smoke test for every inventory host:

uv run ansible-playbook playbooks/ping.yaml
uv run ansible-playbook playbooks/ping.yaml --limit crosshost

apply.yaml

The generic play. It does not contain mode-specific data: it reconciles whatever the selected hosts declare in group_vars/.

# Play Hosts Serial Tag
1 Validate the add-on selection all – always
2 Install and configure pgcli all – pgcli
3 PostgreSQL instances all 1 instance
4 Host daemons all – daemon
5 Add-ons all 1 addon
6 Assemble the Redis cluster all – addon
7 Patroni HA members ha_cluster 1 ha
8 Patroni HA backup convergence ha_cluster – ha
9 Patroni HA proxy proxy host – ha, haproxy

serial: 1 is deliberate: the first host installs the add-ons or bootstraps etcd, then the next host joins; cross-host replicas need their primary to exist first.

Add-ons are selected with --limit addon_<type>_<single|cluster>; group_vars/all reads that group’s addon_<kind>_addons list into pgcli_addons. A limit that starts with addon_ but is not one exact existing group with a mode suffix fails the validation play, and a group name that does not exist fails while Ansible matches the limit. Without such a limit the list is empty and the add-on play is a no-op.

The Redis assembly play runs after all members exist (the add-on play is serial). It only acts when --limit addon_redis_cluster selects present entries: it waits for every member, creates the cluster once if needed, and waits until all 16384 slots are assigned. Reruns skip the create step.

# Full stack for one deployment mode
uv run ansible-playbook playbooks/apply.yaml --limit crosshost

# Only reconcile instances (pgcli must already be installed/configured)
uv run ansible-playbook playbooks/apply.yaml --limit single --tags instance

# Only reconcile host daemons (for example the Alertmanager webhook)
uv run ansible-playbook playbooks/apply.yaml --limit observable --tags daemon

# Fresh host: install and create in one pass
uv run ansible-playbook playbooks/apply.yaml --limit single --tags pgcli,instance

# Add-ons only, one group (set its entries to absent to remove them)
uv run ansible-playbook playbooks/apply.yaml --limit addon_etcd_cluster --tags addon

# HA members + converge; HAProxy has its own tag
uv run ansible-playbook playbooks/apply.yaml --tags ha
uv run ansible-playbook playbooks/apply.yaml --tags haproxy

# Single host
uv run ansible-playbook playbooks/apply.yaml --limit db-01 --tags instance

Tags do not pull in their prerequisites. A first HA deployment needs the etcd add-on play (pgcli,addon,ha or a full run) before --tags ha can succeed. The HA plays only run on hosts present in [ha_cluster]; the add-on play reconciles etcd on [ha_etcd] hosts.

deploy-s3.yaml

Deploys a standalone S3-compatible store (minio, silo or rustfs) used as the pgBackRest s3 backup target. The store type comes from the active store-type group under [s3]; pgcli_s3_type is optional and must agree.

# Whole active store group
uv run ansible-playbook playbooks/deploy-s3.yaml

# Pick the store type explicitly
uv run ansible-playbook playbooks/deploy-s3.yaml -e pgcli_s3_group=minio_s3

# Deploy only a subset of nodes (single node via a one-host pattern)
uv run ansible-playbook playbooks/deploy-s3.yaml -e pgcli_s3_nodes=db-01
uv run ansible-playbook playbooks/deploy-s3.yaml -e pgcli_s3_nodes=db-01,db-02

# Force container recreation
uv run ansible-playbook playbooks/deploy-s3.yaml -e pgcli_s3_force=true

Layout (single/multi-node, drives) and TLS options are on the S3 storage page.

ha-status.yaml

Read-only. Prints the live Patroni topology (role, state, LSN, lag) and the HAProxy instances in front of each cluster. It runs once on the first selected host; any member can read the shared DCS view.

uv run ansible-playbook playbooks/ha-status.yaml
uv run ansible-playbook playbooks/ha-status.yaml -l ha_cluster
uv run ansible-playbook playbooks/ha-status.yaml -l db-02

resources.yaml

Read-only. Reports CPU, load, memory, swap, filesystems and the top memory processes, plus the pgcli version and, for every namespace in pgcli_namespaces, its instances, add-ons, Patroni status and pg http file servers. HTTP server URLs on the wildcard address are rewritten to the host’s private_ip (falling back to ansible_host). Hosts without the pgcli binary at pgcli_install_path are skipped with a short message.

uv run ansible-playbook playbooks/resources.yaml
uv run ansible-playbook playbooks/resources.yaml -e HOSTS=db-01
uv run ansible-playbook playbooks/resources.yaml -l addon_etcd_single

passwords.yaml

Read-only. Prints the stored credentials for the selected hosts:

  • the admin DSN of each instance, read from pg status -i; 127.0.0.1/localhost in the DSN is rewritten to the host’s private_ip (falling back to ansible_host) so the DSN can be used from another machine;
  • each Patroni cluster’s stored password set (pg ha passwords <scope>);
  • the add-on credentials (pg addon list --show-password).

Every namespace in pgcli_namespaces is reported separately, using that namespace’s own config.

The output is plaintext credentials, so the playbook refuses to run unless Ansible logging is disabled. Pass ANSIBLE_LOG_PATH=/dev/null explicitly:

ANSIBLE_LOG_PATH=/dev/null uv run ansible-playbook playbooks/passwords.yaml
ANSIBLE_LOG_PATH=/dev/null uv run ansible-playbook playbooks/passwords.yaml -e HOSTS=db-01
ANSIBLE_LOG_PATH=/dev/null uv run ansible-playbook playbooks/passwords.yaml -e HOSTS=ha_cluster

Do not redirect its stdout to a world-readable file; write any copy to a 0600 file or a password manager.

Idempotency

Re-running any playbook is safe. Every state-changing task checks the current pgcli config and container state, so an unchanged host reports ok. The exception is pgcli_install_force: true, which re-runs the installer on every pass by design.

Lifecycle switches

Resource Declaration Default absent effect
Instance pgcli_instances[].state started Removes container + config; with clean_data: true also deletes data/WAL dirs and the pgBackRest stanza
Add-on pgcli_addons[].state present Removes the add-on container + config entry; clean_data applies where the add-on supports it
HA cluster pg_ha_clusters[].state started Removes local members and clears the DCS scope; clean_data: true deletes member data dirs (empty addon/patroni/<scope> dir remains)
HAProxy pg_ha_haproxy.clusters[].state present Removes the proxy instance from the proxy host and prunes its config

Destroy order for HA: HAProxy → Patroni clusters → etcd. etcd is an add-on entry (pgcli_addons[].state); its removal always deletes the data dir. Backup containers, pgBackRest configuration and S3 backups are not removed by the HA plays. S3 stores are deploy-only in this playbook; remove one with pg addon remove <type> --name <name> --clean-data on the node.

Logs

ansible.cfg writes the run log to var/ansible.log and caches facts under var/facts/. Both are gitignored, as are all live main.yml and secrets.yaml files. passwords.yaml overrides the log with ANSIBLE_LOG_PATH=/dev/null because its output contains plaintext credentials.

8 - Instances and replicas

Configure the single, samehost and crosshost example files — every pgcli_instances field, namespaces and state semantics

PostgreSQL instances are declared in pgcli_instances, normally in one deployment-mode group’s group_vars/<mode>/main.yml. apply.yaml --tags instance (run with serial: 1) reconciles each host’s entries whose host: matches that host.

The three mode examples

Each example file is small; copy the one matching the mode you exercise.

group_vars/single/main.yml.example

One stand-alone primary:

pgcli_config_overrides:
  namespace: dev

pgcli_instances:
  - name: pg_single
    host: db-01
    state: started
    autostart: true

group_vars/samehost/main.yml.example

Primary and a read-only replica on the same host:

pgcli_instances:
  - name: pg01
    host: db-01
    state: started
    autostart: true

  - name: pg01_ro1
    host: db-01
    replica_of: pg01
    state: started
    autostart: true

A same-host replica inherits its primary’s namespace; give it the same namespace only if you set one explicitly.

group_vars/crosshost/main.yml.example

The replica lives on another host and names both the primary instance and its host:

pgcli_instances:
  - name: pg01
    host: db-01
    namespace: dev
    state: started
    autostart: true

  - name: pg01_ro1
    host: db-02
    replica_of: pg01
    replica_of_host: db-01
    namespace: dev
    state: started
    autostart: true

The primary’s host must come first in [crosshost]: the play is serial, and the replica needs its primary running. The role prepares the primary side (replication slot + pg_hba) before creating the replica with --primary-dsn, reading the primary password from that host’s pg.yaml.

pgcli_instances fields

Field Applies to Meaning
name all Required instance name
host all Inventory host that owns the instance
namespace all Name from pgcli_namespaces; omit for the host default
state all present, started (default), stopped, absent
autostart all Enable the instance at boot (pg autostart enable)
backup_target primary local (default) or s3; fixed at creation time
password_length primary Generated admin password length (default 16)
extensions primary Extension list (default pg_stat_statements); setting it replaces the default list
clean_data all Only with state: absent; also deletes data/WAL dirs and the stanza
replica_of replica Name of the primary
replica_of_host replica Inventory host of a cross-host primary

Replica entries accept only name, replica_of, replica_of_host, namespace, state, autostart and clean_data. Password, database, image, extension and PITR settings are inherited from the primary.

Defaults come from pgcli_instance_defaults in group_vars/all/main.yml:

pgcli_instance_defaults:
  state: started
  autostart: false
  backup_target: local
  password_length: 16
  extensions:
    - pg_stat_statements
  clean_data: false

State semantics

  • present creates the instance without changing its run state.
  • started creates (if needed) and starts it.
  • stopped creates (if needed) and stops it.
  • absent removes the container and the config entry. The data and WAL directories and the pgBackRest stanza are kept unless clean_data: true. A full destroy therefore needs both: state: absent and clean_data: true; clean_data alone does nothing.

Namespaces

pgcli_namespaces maps a selector name to a directory holding pg.yaml:

pgcli_namespaces:
  - name: dev
    path: /root/.pgcli
  - name: prod
    path: /root/.pgcli/prod

Instances select one with namespace: <name>; omitted means the host default (pgcli_namespace_path / pgcli_config_path). Extra entries with their own base_dir are initialized automatically by the pgcli role; entries without base_dir need a manual pg config init -o.

Run it

# Full mode (installs pgcli if needed)
uv run ansible-playbook playbooks/apply.yaml --limit samehost

# Instances only on an already prepared host
uv run ansible-playbook playbooks/apply.yaml --limit crosshost --tags instance

Re-running is idempotent; instances already in the desired state report ok.

9 - Observability deployment

Manage many machines with one declarative Ansible scenario: node and PostgreSQL exporters, Prometheus, alert rules, Alertmanager, and a pg daemon webhook receiver

The observable scenario turns a fleet of machines into a monitored data center: every member runs node_exporter, PostgreSQL hosts also run pg_exporter, and one host runs Prometheus, Alertmanager, Grafana, and the alert webhook. Instances, add-ons, and the webhook process are declared in group variables and converged by one apply.yaml run. Adding machines means adding inventory entries and re-running the playbook — no per-host commands.

The shipped reference is group_vars/observable/main.yml.example; group_vars/observable/README.md contains the full Grafana API walkthrough.

Reference layout

Host Role
db-01 stand-alone instance pg01, nodeexporter, pgexporter
db-02 primary pg02, nodeexporter, pgexporter
db-03 cross-host read-only replica pg_primary_ro1, nodeexporter, pgexporter
obs-01 nodeexporter, prometheus, alertmanager, grafana, alertmanager-webhook daemon

For a larger fleet the layout is the same: list every machine in [observable], add its PostgreSQL instances to pgcli_instances, and the scrape targets are derived from the inventory. All playbook commands run from the ansible/ directory.

Inventory for many machines

[all]
db-01 ansible_host=192.0.2.11 private_ip=192.0.2.11
db-02 ansible_host=192.0.2.12 private_ip=192.0.2.12
db-03 ansible_host=192.0.2.13 private_ip=192.0.2.13
db-04 ansible_host=192.0.2.15 private_ip=192.0.2.15
obs-01 ansible_host=192.0.2.14 private_ip=192.0.2.14

[all:vars]
ansible_user=root
ansible_port=22

# Every monitored machine belongs to this group. node_exporter is installed on
# all of them; the observability host is included too.
[observable]
db-01
db-02
db-03
db-04
obs-01

[observable:vars]
ansible_group_priority=20

# Optional subgroups for batched rollouts and environment labels. They do not
# replace [observable]: group_vars/observable still applies to these hosts.
[rack-a]
db-01
db-02
[rack-b]
db-03
db-04
obs-01

private_ip is the address used for node-to-node scraping and replication. ansible_host is only the SSH target. Keeping both lets the monitoring traffic stay on the private network.

Custom group names

observable is only the shipped example name. For a real site, copy the group variable file under a name that matches your inventory group:

cp group_vars/observable/main.yml.example group_vars/site-a/main.yml
cp group_vars/observable/main.yml.example group_vars/site-b/main.yml

Then declare the same group names in hosts.ini:

[site-a]
db-01
db-02
obs-01

[site-b]
db-10
db-11
obs-02

[site-a:vars]
ansible_group_priority=20
[site-b:vars]
ansible_group_priority=20

Run --limit site-a or --limit site-b. Group variables follow membership, so each site gets its own pgcli_instances, pgcli_addons, and optionally pgcli_daemons; hosts shared by two scenario groups should be avoided, because the lists do not merge — the winning group is decided by Ansible’s group precedence. Do not name a scenario group with an addon_ prefix; those names are reserved for the addon_<type>_<single|cluster> selector. Keep the example files’ host: values in sync with the hostnames used in the new group, replace groups['observable'] in _observable_node_exporter_targets with the new group name, and create group_vars/<group>/secrets.yaml with pgexporter_monitor_password (gitignored, as described below).

Targets and labels

The example derives both scrape jobs from the inventory:

# Hosts running node_exporter: every member of [observable].
_observable_node_exporter_targets: >-
  {{ groups['observable'] | map('extract', hostvars, 'private_ip')
     | map('regex_replace', '$', ':9100') | join(',') }}

# Hosts running pg_exporter: one per host that carries a pgcli instance.
_observable_pg_exporter_targets: >-
  {{ pgcli_instances | map(attribute='host') | unique
     | map('extract', hostvars, 'private_ip')
     | map('regex_replace', '$', ':9630') | join(',') }}

Both are passed to Prometheus as --scrape <job>=<targets> and regenerated on every apply, so a machine added to [observable] (or an instance added to pgcli_instances) is picked up automatically. This is static scrape configuration, not service discovery: Prometheus is told exact host:port targets.

To attach labels such as the environment or rack, pass KEY=VALUE tokens after the target list. The flag accepts one --scrape per label set; a compact way to build one spec per group:

_observable_node_scrapes: >-
  {{ (['--scrape'] | product([
       'node-exporter=' ~ (groups['rack-a'] | map('extract', hostvars, 'private_ip')
                            | map('regex_replace', '$', ':9100') | join(',')) ~ ' rack=rack-a',
       'node-exporter=' ~ (groups['rack-b'] | map('extract', hostvars, 'private_ip')
                            | map('regex_replace', '$', ':9100') | join(',')) ~ ' rack=rack-b'
     ])) | list | flatten }}

Then place _observable_node_scrapes into the add-on’s params instead of the single --scrape entry. The same labels are available to alert rules as $labels.rack.

nodeexporter has no host key in its add-on entry, so it installs on every member. If a machine should be monitored without running PostgreSQL, put it in [observable] only; it contributes a node_exporter target and no pg target.

Group variables and secrets

cp group_vars/observable/main.yml.example group_vars/observable/main.yml

The scenario sets pgcli_deploy_rootless: true and pgcli_deploy_user: pgcli, so pgcli, podman, containers, and the webhook daemon all run as the unprivileged pgcli account. Derived paths follow pgcli_deploy_home.

Instances for the whole fleet are declared once in this group’s pgcli_instances list (name, host, optional replica settings). Each host reconciles only the entries whose host matches. Use host_vars/<host>.yml for per-machine overrides rather than copying the group file.

All PostgreSQL exporters share one low-privilege monitor role. On primaries and stand-alone instances pgexporter creates the role (pg_monitor, CONNECTION LIMIT 5) with the password pinned from group_vars/observable/secrets.yaml (gitignored, never committed):

pgexporter_monitor_password: "<choose a strong value>"

A physical standby cannot run the role-creation SQL. Streaming replication carries the role created on the primary, and the standby’s exporter dials the local port with --dsn using the same password. Keep the default role name pgexporter; a renamed role would have to be created on the primary and replicated again.

Deploy in batches

cd ansible
uv sync
uv run ansible-playbook playbooks/apply.yaml --limit observable

The instance and add-on plays run serial: 1, so large groups are provisioned one host at a time. For a multi-rack rollout, select a subgroup per window — --limit rack-a still applies group_vars/observable because group variables follow membership, not the limit:

uv run ansible-playbook playbooks/apply.yaml --limit rack-a
# verify Prometheus targets, then:
uv run ansible-playbook playbooks/apply.yaml --limit rack-b

Partial runs by tag:

uv run ansible-playbook playbooks/apply.yaml --limit observable --tags instance  # instances
uv run ansible-playbook playbooks/apply.yaml --limit observable --tags addon     # exporters + stack
uv run ansible-playbook playbooks/apply.yaml --limit observable --tags daemon    # webhook receiver

The playbook order is install → instances → daemons → add-ons. Every role compares declared state with pg config show and container state, so unchanged hosts report ok. force: true on the Prometheus and Alertmanager entries recreates those containers so changed parameters (--scrape, --webhook-url, rules) take effect; without it an installed add-on keeps its original flags. Recreating Prometheus is intentional here because its scrape targets are inventory-derived and change whenever the fleet changes.

Prometheus capacity

A single Prometheus add-on scrapes the whole fleet. Size it deliberately:

  • --retention 15d is the default; raise it (for example 30d) or set an explicit --data-dir on a large disk for long local history.
  • --scrape-interval 15s is the default; on a large fleet, 30s or 60s cuts samples proportionally.
  • The local TSDB is single-instance; the add-on does not cluster. For longer retention or cross-site aggregation, add --remote-write-url pointing at a VictoriaMetrics add-on and keep the local retention short. The write queue replays after a remote outage.
  • Prometheus has no authentication. Keep --listen=127.0.0.1 as in the example and let Grafana proxy queries, or firewall the port.

Remote-write long-term example

Add a single-node VictoriaMetrics instance on the observability host and make Prometheus push a copy of every sample to it:

  # node4: long-term storage. No auth, so bind loopback only.
  - type: victoriametrics
    name: victoriametrics
    host: node4
    state: present
    force: true
    params:
      - "--listen=127.0.0.1"
      - "--retention-months=12"

  - type: prometheus
    name: prometheus
    host: node4
    state: present
    force: true
    params:
      - "--listen=127.0.0.1"
      - "--alertmanager-url"
      - "127.0.0.1:9093"
      # Inventory-derived scrape parameters stay as they are...
      - "--scrape"
      - "node-exporter={{ _observable_node_exporter_targets }}"
      - "--scrape"
      - "pg={{ _observable_pg_exporter_targets }}"
      # the rule_files mapping stays as it is...
      # Full URL; the path is the write endpoint (single-node uses
      # /api/v1/write; vmcluster's vminsert uses
      # :8480/insert/0/prometheus/api/v1/write).
      - "--remote-write-url"
      - "http://127.0.0.1:8428/api/v1/write"
      # Optional: batch tuning suggested by VictoriaMetrics under load.
      - "--remote-write-queue"
      - "max_samples_per_send=10000"
      - "--remote-write-queue"
      - "capacity=20000"
      - "--remote-write-queue"
      - "max_shards=30"

Both containers use host networking, so loopback is reachable. remote_write is a copy, not a migration: the local TSDB still retains and serves data per its own --retention. If you rely on VictoriaMetrics for long-term data, shorten Prometheus’s --retention (for example 7d) so the local disk does not grow without bound. A remote outage only stalls the write queue; it replays once the remote returns.

Add http://127.0.0.1:8428 as a second Prometheus-type data source in Grafana to query history beyond the local retention; VictoriaMetrics accepts PromQL. Verify the pipeline:

# the queue is draining and samples keep flowing
curl -s 'http://127.0.0.1:9090/api/v1/query?query=prometheus_remote_storage_samples_pending'
# samples have landed in VictoriaMetrics
curl -s 'http://127.0.0.1:8428/api/v1/query?query=prometheus_build_info'

Alerting rules and routing

Prometheus loads misc/prometheus/postgres.rules.yml through the rule_files mapping on the Prometheus entry. The pg_addon role copies the file into pgcli’s managed rules directory and passes --rule-file at install time. Rule content lives in a real file so Prometheus’s own {{ $labels.* }} templating is never re-rendered by Ansible. The rules cover PostgreSQL (pg_up, replication lag, paused replay, connection saturation, idle-in-transaction, deadlocks, archiver failures), node targets (scrape failures, CPU and memory pressure, disk space, read-only filesystems), and Alertmanager config reloads.

Firing alerts go to Alertmanager, whose only receiver is the webhook managed by pg daemon:

Item Value
Script misc/webhook/alertmanager_webhook.py (copied to the daemon dir)
Command /usr/bin/python3 <daemon dir>/alertmanager_webhook.py --listen 127.0.0.1:18801
Log <daemon dir>/logs/alertmanager-webhook.log
Rotation 10 MB, keep 7
Autostart enabled

The receiver prints one JSON line per alert and suppresses HTTP access logs, so the daemon log contains only alert messages. Inspect it as the deployment account on the observability host:

runuser -u pgcli -- /usr/local/bin/pg -c /home/pgcli/.pgcli/pg.yaml \
  daemon status alertmanager-webhook
runuser -u pgcli -- /usr/local/bin/pg -c /home/pgcli/.pgcli/pg.yaml \
  daemon logs alertmanager-webhook -n 50
runuser -u pgcli -- /usr/local/bin/pg -c /home/pgcli/.pgcli/pg.yaml \
  autostart status

pg autostart status shows daemon alertmanager-webhook enabled; at boot, pg start --autostart starts instances first, then add-ons, then daemons.

The rendered Alertmanager config has one route and one receiver. For severity/team routing, give the add-on entry a full conf (written 0600 and passed as --conf-file; keep secrets in the gitignored live file):

  - type: alertmanager
    name: alertmanager
    host: obs-01
    state: present
    force: true
    params:
      - "--listen=127.0.0.1"
    conf: |
      route:
        receiver: default
        group_by: [alertname, env]
        routes:
          - matchers: ['severity="critical"']
            receiver: oncall
      receivers:
        - name: default
          webhook_configs:
            - url: http://127.0.0.1:18801/alertmanager
        - name: oncall
          webhook_configs:
            - url: http://127.0.0.1:18801/alertmanager

The bundled receiver accepts POST /alertmanager and GET /health; to distinguish receiver names, extend deliver() or point oncall at an external API. The Alertmanager add-on runs a single instance and disables cluster gossip, so it is not HA — keep its data directory (silences survive container recreation) and restart the add-on if the host is lost.

To forward alerts to a third-party API, implement the HTTP call in deliver() inside misc/webhook/alertmanager_webhook.py. Return False to answer 503 and let Alertmanager retry. Keep tokens out of the repository: read them from a 0600 file owned by the deployment account. Alertmanager groups notifications, so deduplicate on alert["fingerprint"] when the target API is not idempotent. Rerunning --tags daemon rewrites the script and restarts the daemon when its content changed.

Verify

Run the loopback probes on the observability host:

curl -sS http://127.0.0.1:9090/api/v1/targets \
  | jq -r '.data.activeTargets[] | "\(.labels.job)\t\(.labels.instance)\t\(.health)"'
curl -sS http://127.0.0.1:9090/api/v1/targets \
  | jq '[.data.activeTargets[] | select(.health != "up")] | length'
curl -sS http://127.0.0.1:9090/api/v1/rules \
  | jq -r '.data.groups[].rules[] | "\(.name)\t\(.health)"'
curl -sf -o /dev/null -w '%{http_code}\n' http://127.0.0.1:9093/-/ready
curl -sS http://127.0.0.1:18801/health

Every target should report up (the count of non-up targets is 0), every rule ok, Alertmanager 200, and the webhook {"status":"ok"}. Send a synthetic alert through Alertmanager; it appears in the daemon log after the default group_wait (about 30 seconds):

curl -sS -X POST http://127.0.0.1:9093/api/v2/alerts \
  -H 'Content-Type: application/json' \
  -d '[{"labels":{"alertname":"WebhookTest","severity":"warning"},
        "annotations":{"summary":"test"}}]'

Send the same alert with an endsAt in the past to resolve it.

Grafana

Grafana generates its admin password; retrieve it without writing it to the Ansible log:

GF_PASSWORD=$(ANSIBLE_LOG_PATH=/dev/null uv run ansible-playbook playbooks/passwords.yaml \
  -e HOSTS=obs-01 | sed -n 's/^ *Login password: //p')
GRAFANA=http://obs-01:3000

Create the Prometheus data source (the URL is loopback because both containers use host networking), then import the two dashboards:

curl -sS -u "admin:$GF_PASSWORD" \
  -H 'Content-Type: application/json' \
  -X POST "$GRAFANA/api/datasources" \
  --data '{
    "name": "Prometheus",
    "type": "prometheus",
    "url": "http://127.0.0.1:9090",
    "access": "proxy",
    "isDefault": true,
    "editable": true,
    "jsonData": {"httpMethod": "POST"}
  }'

curl -sS -o /tmp/node-exporter-full.json \
  https://grafana.com/api/dashboards/1860/revisions/latest/download
jq --arg ds Prometheus '
  .templating.list |= map(
    if .name == "ds_prometheus"
    then .current = {selected: true, text: $ds, value: $ds}
    else . end)
  | {dashboard: ., overwrite: true, folderId: 0}
' /tmp/node-exporter-full.json > /tmp/node-exporter-import.json
curl -sS -u "admin:$GF_PASSWORD" -H 'Content-Type: application/json' \
  -X POST "$GRAFANA/api/dashboards/db" --data @/tmp/node-exporter-import.json

jq -n --slurpfile d misc/grafana/postgresql-pgexporter.json \
  '{dashboard: $d[0], overwrite: true, folderId: 0}' > /tmp/pg-dashboard-import.json
curl -sS -u "admin:$GF_PASSWORD" -H 'Content-Type: application/json' \
  -X POST "$GRAFANA/api/dashboards/db" --data @/tmp/pg-dashboard-import.json

The repository dashboard is named Pgcli PostgreSQL and has the fixed UID pgcli-pgexporter, so the second import updates it in place. The Node Exporter Full dashboard keeps the UID from its JSON. A repeat data source POST returns HTTP 409; the existing data source is then reused. The Instance variable defaults to the first PostgreSQL target; select All or add more instances from the picker when managing many databases.

Security notes

  • Keep Prometheus, Alertmanager, and the webhook on loopback. Alertmanager’s silence API is as sensitive as a notification channel.
  • pgexporter on port 9630 is unauthenticated; restrict it to the monitoring network with the host firewall.
  • The monitor password, Alertmanager routing secrets, and any third-party API token stay outside the repository (secrets.yaml is gitignored; the webhook reads its token from a 0600 file).
  • A machine that is removed from [observable] also disappears from the Prometheus scrape list on the next apply; its nodeexporter container is removed only if you run an explicit remove/absent state for it.

10 - Add-ons

Configure addon__ groups — install and remove top-level or instance-scoped add-ons, and manage the shared etcd group

Add-ons are declared as addon_<group>_addons lists in group_vars/addon_<type>_<mode>/main.yml. group_vars/all reads the list of the group named by --limit into pgcli_addons, so one run selects one add-on group:

uv run ansible-playbook playbooks/apply.yaml \
  --limit addon_pgbouncer_single --tags addon

The repository ships one group per add-on type and installation form: addon_<type>_single (one host) and addon_<type>_cluster (three or four hosts). See Add-on clusters for the cluster form. The ha_etcd and S3 groups define pgcli_addons directly and keep working the same way. type takes any add-on accepted by pg addon install — see the add-on reference for the full list (pgbouncer, pgdog, etcd, haproxy, minio/silo/rustfs, redis, nginx, prometheus, kafka, and so on).

Entry fields

Field Meaning
type Add-on type accepted by pg addon install (see the add-on reference)
name Top-level add-on instance name (e.g. this etcd member)
pg_name Instead of name: remote PgBouncer/PostgREST target name (--pg-name)
dsn Remote PostgreSQL DSN (--dsn; pgbouncer, postgrest, pgexporter only)
instance Instead of name: scope the add-on to a pgcli instance
state present (default) or absent
params Complete per-entry flag list; replaces addon_<group>_params for this entry
args Per-entry flags appended verbatim after the resolved parameters
conf Inline config content, overriding addon_<group>_conf (nginx, haproxy, privoxy, prometheus, alertmanager only)
clean_data With state: absent, delete data where the add-on supports it (default true; set false to keep it)
force With state: present, recreate with pg addon install --force
autostart true (default) enables boot autostart, false disables it

Every entry needs type and exactly one of name, pg_name, or instance; the role asserts this before doing anything.

Per-type parameters

Flags shared by every entry in one group can be declared once next to the list as addon_<group>_params: a list of raw pg addon install tokens. Entries that do not set their own params inherit this list.

An entry can set params to its own complete flag list. It replaces addon_<group>_params for that entry, so different instances of the same type can use different ports, data directories, memory limits, and so on. Per-entry args is still appended after the resolved params.

addon_redis_single_addons:
  - type: redis
    name: cache
    state: present
    params:
      - "--port"
      - "6379"
      - "--maxmemory"
      - "256mb"
  - type: redis
    name: session
    state: present
    params:
      - "--port"
      - "6380"
      - "--maxmemory"
      - "512mb"
      - "--listen"
      - "127.0.0.1"

Entry names must be unique per type; each instance is stored under addons.<type>.<name> in the pgcli config. Because params replaces the shared list, repeat any shared flags in each entry (or use YAML anchors). The variable name is addon_<group>_params, where <group> is the selected inventory group (for example addon_redis_single_params or addon_clickhouse_keeper_cluster_params). Groups that define pgcli_addons directly fall back to addon_<type>_params.

Inline config files

nginx, haproxy, privoxy, prometheus and alertmanager accept --conf-file. Put the file content in addon_<group>_conf instead of maintaining a path on the target:

addon_haproxy_single_conf: |
  global
      maxconn 1000
  defaults
      mode tcp
      timeout connect 4s
      timeout client 30m
      timeout server 30m
  # ... frontend/backend ...

addon_haproxy_single_addons:
  - type: haproxy
    name: lb1
    state: present

A Privoxy config replaces the rendered template, so it must be complete — the listener and stdout logging are not inherited — and it cannot be combined with --allow-network / --deny-network:

addon_privoxy_single_conf: |
  confdir /etc/privoxy
  logdir /var/log/privoxy
  logfile /dev/stdout
  listen-address 0.0.0.0:8118

  # Plain forward-socks5 resolves hostnames locally; forward-socks5t uses
  # remote DNS.
  forward-socks5 / 127.0.0.1:1080 .

  permit-access 127.0.0.1/32
  permit-access 10.0.0.0/8
  permit-access 172.16.0.0/12
  permit-access 192.168.0.0/16

addon_privoxy_single_addons:
  - type: privoxy
    name: privoxy1
    state: present

The role writes the content to <dir of pgcli_config_path>/addons/<type>-<name>.conf (mode 0600) and passes --conf-file; pg addon install still validates it with haproxy -c / nginx -t. A per-entry conf overrides the group-level value. Inline config cannot be combined with an explicit --conf-file or with flags that render the same file (nginx --upstream, prometheus --scrape/--remote-write-url, alertmanager --webhook-url). Editing the content does not reinstall an existing add-on: set force: true (or remove it first) to apply the change.

Standalone vs cluster installation

Installation describes whether the add-on is installed standalone or as a cluster — not whether several independent copies can run on different hosts:

  • Standalone: only a single-host installation exists. Copies deployed on multiple hosts are independent and do not form a cluster.
  • Standalone + cluster: installable either standalone or in cluster mode.
  • Cluster only: only installable as a cluster (a quorum is required).

This repository ships one standalone group per type — addon_<type>_single, one host each — and, for types that support it, one cluster group — addon_<type>_cluster, three or four hosts. Run one group per invocation with --limit addon_<type>_<mode>; Add-on clusters covers the cluster layouts. The cluster form of each add-on page documents the product flags; the S3 and HA groups are covered in their own pages here.

Add-on Installation Notes
pgbouncer standalone instance-scoped
etcd standalone + cluster --cluster; shared DCS for HA
pgdog standalone + cluster one backend vs sharded backends
haproxy standalone each proxy is independent, no cluster mode
minio standalone + cluster SNSD/SNMD vs MNMD
silo standalone + cluster SNSD/SNMD vs MNMD
rustfs standalone + cluster cluster mode is MNMD only (no MNSD)
garage standalone v1 supports one host only
seaweedfs standalone + cluster weed mini vs weed server
redis standalone + cluster standalone vs --cluster sharding
predixy standalone one proxy fronting one or more Redis backends
postgrest standalone
pgadmin standalone
grafana standalone
prometheus standalone
alertmanager standalone HA gossip disabled by pgcli
victoriametrics standalone
nodeexporter standalone
pgexporter standalone
documentdb standalone requires a local PG 18 instance
vmcluster standalone + cluster all roles on one host vs role split
vlcluster standalone + cluster all roles on one host vs role split
victorialogs standalone
vlagent standalone
vmalert standalone HA via repeated instances and --external-label
influxdb standalone no HA in v1
influx2tsdb standalone
clickhouse standalone + cluster static replicated cluster with Keeper
clickhouse-keeper cluster only Raft quorum of 3 or 5
kafka standalone + cluster KRaft controller quorum
rabbitmq standalone + cluster etcd peer discovery
rocketmq standalone + cluster standalone vs DLedger cluster
gitea standalone
beegfs standalone v1 is one filesystem per host
juicefs standalone host binary; external S3 + metadata
zerofs standalone host binary; external S3
duckdb standalone host binary
nginx standalone one reverse proxy
privoxy standalone HTTP/HTTPS forward proxy; no TLS interception

Top-level add-on example

group_vars/addon_nodeexporter_single/main.yml.example declares a top-level add-on in its group list:

addon_nodeexporter_single_addons:
  - type: nodeexporter
    name: ne1
    state: present

--limit addon_nodeexporter_single makes group_vars/all read that list into pgcli_addons for the single host in the group.

Groups that set pgcli_addons directly use the same entry format. group_vars/ha_etcd/main.yml.example builds one etcd member per host:

pgcli_addons:
  - type: etcd
    name: "etcd-{{ groups[pg_etcd_group].index(inventory_hostname) + 1 }}"
    state: present
    autostart: true
    args: "{{ ['--cluster', 'ha', '--advertise-host', _ha_etcd_advertise_host]
             + (['--join', _ha_etcd_bootstrap_endpoint]
                if inventory_hostname != (groups[pg_etcd_group] | first) else []) }}"

The first host in the group bootstraps the cluster; the rest pass --join to a running member. The add-on play runs with serial: 1, so the bootstrap host is always ready before the next host joins.

Instance-scoped example

Use instance instead of name for add-ons that belong to a PostgreSQL instance. group_vars/addon_pgbouncer_single/main.yml.example declares the instance and the add-on in the same group:

addon_pgbouncer_single_instances:
  - name: your_pg_ins01
    host: "{{ inventory_hostname }}"
    state: started

addon_pgbouncer_single_addons:
  - type: pgbouncer
    instance: your_pg_ins01
    state: present

Run both plays so the instance exists first: --limit addon_pgbouncer_single --tags instance,addon. The role then runs pg addon install pgbouncer -i your_pg_ins01.

Remote PostgreSQL example

Set dsn to target a PostgreSQL server that pgcli does not manage. PgBouncer and PostgREST also need pg_name, the name the remote target is stored under; pgexporter keeps its name. The pgbouncer group ships the remote variant behind addon_pgbouncer_single_remote_dsn: leave it empty to pool the local your_pg_ins01 instance, or set it to skip the instance and pool that server:

addon_pgbouncer_single_addons:
  - type: pgbouncer
    pg_name: remote-proj01
    dsn: postgres://admin:secret@db.example.com:5432/proj01
    state: present

pgexporter is declared the same way in addon_pgexporter_single_addons, but uses name instead of pg_name. A local (no dsn) entry can pin the monitor-role password with --monitor-password-file FILE (or --monitor-password VALUE) in params, so a standby’s dial-as-is dsn entry can reuse the same credential without a post-install fetch. The role sets no_log on the tasks carrying --monitor-password.

These entries are top-level (addons.<type>.<name>), so state: absent and autostart use --pg-name (remote pgbouncer/postgrest) or --name (pgexporter). pgdog has no --dsn flag; pass --backend NAME=HOST:PORT:DB and --user NAME:PASSWORD in params instead.

Multiple entries

Every group list is a YAML list; each item is reconciled in order. The redis example above declares two instances of the same type. Groups that set pgcli_addons directly (for example ha_etcd) can also mix types in one list:

pgcli_addons:
  - type: etcd
    name: etcd-1
    args: [...]
  - type: redis
    name: cache
    state: absent

Install and remove

# Reconcile one standalone add-on group
uv run ansible-playbook playbooks/apply.yaml --limit addon_nginx_single --tags addon

# Reconcile one cluster group
uv run ansible-playbook playbooks/apply.yaml --limit addon_etcd_cluster --tags addon

# The shared etcd DCS group, which defines pgcli_addons directly
uv run ansible-playbook playbooks/apply.yaml --tags addon --limit ha_etcd
  • state: present installs only when the name/instance is missing from the config, unless force: true is set. It also reconciles autostart with pg autostart enable|disable --<type> ...; leaving it unset enables boot autostart for the add-on.
  • state: absent calls pg addon remove <type> --name <name>, --pg-name <pg_name> for remote pgbouncer/postgrest, or -i <instance>; data is deleted by default, and clean_data: false keeps it where the add-on supports that. The etcd remove path always deletes its data directory.
  • Running --tags addon without an addon_* limit leaves pgcli_addons empty for the add-on groups, so the run is a no-op there; groups that define pgcli_addons directly (ha_etcd, S3) still reconcile.

etcd lifecycle

The etcd entry’s state controls the member lifecycle: present (the add-on default) creates/reconciles the local member, absent removes it.

Set it to absent only after the Patroni clusters are gone: they use this etcd as their DCS. With serial: 1, members are removed one host at a time; etcd removal deletes the data directory as part of the command. To rebuild, set it back to present and re-run --tags addon — the first host bootstraps, the rest rejoin.

11 - Add-on clusters

Deploy multi-host add-on clusters with one inventory group per type — shared secrets and TLS material, quorum layouts and lifecycle

The addon_<type>_cluster inventory groups deploy one cluster-capable add-on across several hosts. They are the multi-host companion of Add-ons: the entry fields (type, name, state, params, args, clean_data, force, autostart) are the same, but the host lists, peer arguments and shared secrets are derived from the inventory instead of being written per host.

The groups are deliberately not a “deploy everything” group. The reference VMs are small, so one add-on type is reconciled per run and every command selects its group with --limit addon_<type>_cluster.

Inventory and variables

hosts.ini defines the four hosts once in [all], then selects them by bare name into one group per add-on type. Quorum add-ons use three hosts; MinIO/silo MNSD and the other four-member layouts use all four:

[all]
node1 ansible_host=192.0.2.10 private_ip=192.0.2.10
node2 ansible_host=192.0.2.11 private_ip=192.0.2.11
node3 ansible_host=192.0.2.12 private_ip=192.0.2.12
node4 ansible_host=192.0.2.13 private_ip=192.0.2.13

[all:vars]
ansible_user=root
ansible_port=22

[addon_etcd_cluster]
node1
node2
node3

[addon_minio_cluster]
node1
node2
node3
node4

private_ip is required: peer arguments, advertised addresses and the shared certificate SANs all use it. Host order matters — the add-on play runs with serial: 1 in inventory order, so the first host bootstraps the quorum before the others join.

Each group has its own self-contained group_vars directory. Copy the ones you use and edit them:

cd ansible
cp group_vars/addon_etcd_cluster/main.yml.example \
   group_vars/addon_etcd_cluster/main.yml

main.yml is gitignored; it holds the environment-specific values (the SeaweedFS metadata DSN, any explicit passwords). Each file declares its topology variables and one addon_<group>_addons list, so a reader sees everything that add-on needs in one place:

_addon_cluster_etcd_hosts: "{{ groups['addon_etcd_cluster'] }}"
_addon_cluster_etcd_index: "{{ _addon_cluster_etcd_hosts.index(inventory_hostname) | int }}"

addon_etcd_cluster_addons:
  - type: etcd
    state: present
    name: "etcd-{{ (_addon_cluster_etcd_index | int) + 1 }}"

The type name uses - replaced by _ in group and variable names: addon_clickhouse_keeper_cluster_addons targets clickhouse-keeper.

Each list entry follows the fields documented on Add-ons; state is set directly on each entry:

  • present installs the member, or keeps it if it already exists.
  • absent removes the member. Its data is deleted too unless the entry sets clean_data: false.

The runtime selector is playbook plumbing, not add-on configuration (group_vars/all/main.yml):

_addon_limit: "{{ ansible_limit | default('', true) }}"
_addon_group: >-
  {{ _addon_limit
     if (_addon_limit is match('^addon_[A-Za-z0-9_]+$') and _addon_limit in groups)
     else '' }}
_addon_kind: "{{ _addon_group | regex_replace('^addon_', '') }}"
_addon_type: "{{ _addon_kind | regex_replace('_(single|cluster)$', '') }}"
_addon_mode: >-
  {{ 'cluster' if _addon_kind is match('.*_cluster$')
     else ('single' if _addon_kind is match('.*_single$') else '') }}
pgcli_addons: >-
  {{ lookup('vars', 'addon_' ~ _addon_kind ~ '_addons', default=[])
     if _addon_group | length > 0 else [] }}

--limit addon_etcd_cluster expands pgcli_addons to addon_etcd_cluster_addons on those three hosts; without an add-on limit the list is empty, so the play is a no-op. apply.yaml rejects wildcards, comma-separated lists and addon_<type> names without a mode suffix.

Shared material

Multi-member add-ons need a common password and, optionally, a common TLS certificate. roles/addon_cluster_shared generates this once on the controller (the machine running ansible-playbook) before pg_addon runs on each member:

Material Location
Random passwords (minio_root_password, silo_root_password, rustfs_root_password, seaweedfs_root_password, redis_password, clickhouse_admin_password) var/addon_cluster/shared/ on the controller
Shared CA (ca.crt, ca.key), server key/CSR/certificate, chain and combined PEM same directory; the CA private key never leaves the controller
RabbitMQ Erlang cookie and admin password generated by pg addon rabbitmq secret generate and published to etcd

On the members the files land under /data/pg/addon/shared/ (ca.crt, server-chain.crt, server.key, server.pem; private files are 0600). The server certificate covers every private_ip of the selected addon_<type>_cluster group.

Password values are loaded into the matching _addon_cluster_<type>_* variables with set_fact during the run, so the templates keep them empty:

_addon_cluster_minio_root_user: admin
_addon_cluster_minio_root_password: ""

Set the add-on’s own _tls: true switch to use the shared certificate where the type supports it (minio, silo, rustfs, seaweedfs, kafka, rabbitmq). The install summary then prints https:// endpoints; pg mc adds --insecure for the self-signed CA.

RabbitMQ is the exception: its cookie and admin password must be identical on every member, so the role publishes them to etcd under /pgcli/rabbitmq/clusters/<name>/secrets/ and each member installs with --secrets-from-etcd. This requires a running etcd cluster; deploy the etcd section first. The generation command runs on the controller, so the controller needs the pg binary at pgcli_install_path and must reach the first endpoint in _addon_cluster_rabbitmq_etcd_endpoints.

Shipped layouts

Type Members Ports Notes
etcd first 3 2379 client, 2380 peer first host bootstraps, the rest --join it
minio 4 9100 API, 9101 console MNSD; each node contributes its own /data
silo 4 9200 API, 9201 console MNSD
rustfs 4 9300 API, 9301 console MNMD; one drive per node. Raw SigV4 requests need an x-amz-content-sha256 header
seaweedfs first 3 8400 master, 8401 volume, 8402 filer, 8403 S3 masters must be an odd count; the filer metadata database must exist in PostgreSQL first
redis 4 6379 (+ cluster bus 16379) installs four cluster-enabled members; apply.yaml assembles the slots and waits for a healthy cluster afterwards
clickhouse-keeper first 3 9181 client, 9234 Raft 3-member Raft quorum; --server-id = host index + 1
clickhouse 4 8123 HTTP, 9000 native, 9009 interserver 2 shards × 2 replicas over the Keeper above; deploy Keeper first
kafka first 3 9092 broker, 19093 controller KRaft quorum; 512 MiB heap fits the reference VMs
rabbitmq first 3 5672 AMQP, 15672 management needs etcd; shared cookie/password come from etcd
rocketmq first 3 9876 namesrv, 10911 broker, 8080 proxy, 8081 gRPC reduced heaps for small hosts
vmcluster 4 8480 insert, 8481 select, 8482 storage, 8483/8484 internal first host runs storage+insert+select, the rest storage only
vlcluster 4 9430 insert, 9431 select, 9432 storage same access/storage split; storage is sharded without replication

The three-node layouts (addon_etcd_cluster, addon_seaweedfs_cluster, addon_clickhouse_keeper_cluster, addon_kafka_cluster, addon_rabbitmq_cluster, addon_rocketmq_cluster) list only the first three hosts in hosts.ini, so their group files need no [:3] slices or state expressions. The four-member layouts list all four hosts. MinIO/silo MNSD needs at least four endpoints; Redis, vmcluster and vlcluster also use all four.

Create, verify, destroy

Run one type at a time:

cd ansible
uv run ansible-playbook playbooks/apply.yaml --limit addon_etcd_cluster \
  --tags addon

The play is serial: 1 and follows inventory order. For quorum add-ons, the first host must be up before the joiners, so do not reorder hosts between runs.

Verify

Run these on a member unless noted otherwise.

Type Command
etcd pg etcdctl endpoint health and pg etcdctl member list
minio / silo / rustfs / seaweedfs pg mc against the API port, then read the object back through a second member (see below)
redis pg redis-cli -- --cluster check 192.0.2.10:6379 (the play runs the equivalent check after assembly)
clickhouse-keeper pg addon clickhouse-keeper status --name keeper-cluster
clickhouse pg addon clickhouse cluster status --name clickhouse-cluster
kafka pg addon kafka cluster status --name kafka-cluster; pg addon kafka topic list --name kafka-cluster
rabbitmq pg addon rabbitmq cluster status --name rabbitmq-cluster
rocketmq pg addon rocketmq cluster status --name rocketmq-cluster
vmcluster insert a sample then query it through vmselect (see below)
vlcluster insert a sample then query it through vlselect (see below)

Cross-node S3 read (same password on every member, generated on the controller):

PW=$(cat var/addon_cluster/shared/minio_root_password)
pg mc alias set n1 http://192.0.2.10:9100 admin "$PW"
pg mc mb n1/demo
pg mc cp /etc/hostname n1/demo/
pg mc alias set n2 http://192.0.2.11:9100 admin "$PW"
pg mc cat n2/demo/hostname

Use port 9200 for silo, 9300 for rustfs and 8403 for seaweedfs (and the matching password file).

Redis needs no manual step: apply.yaml waits for every member, runs --cluster create ... --cluster-yes once when the cluster has not been assembled yet (passing --cluster-replicas from the add-on params, default 0), then waits until cluster_state:ok reports all 16384 slots across the expected number of nodes. A rerun skips the create step once the cluster is healthy. A partially joined cluster is not reset automatically: the play stops and asks you to reset the members and rerun. The equivalent commands for installs driven by pg addon alone:

pg redis-cli -- --cluster create \
  192.0.2.10:6379 192.0.2.11:6379 192.0.2.12:6379 192.0.2.13:6379 \
  --cluster-replicas 0 --cluster-yes
pg redis-cli -- --cluster check 192.0.2.10:6379

--cluster-yes is required in non-interactive runs: without it redis-cli prompts for confirmation and exits without applying the plan.

VictoriaMetrics cluster:

curl -s -X POST http://192.0.2.10:8480/insert/0/prometheus/api/v1/import/prometheus \
  --data-binary 'demo_metric{host="node1"} 42'
curl -s 'http://192.0.2.10:8481/select/0/prometheus/api/v1/query?query=demo_metric'

The first query can return an empty result while vminsert is still dialing every vmstorage node; retry after a few seconds.

VictoriaLogs cluster:

curl -s -X POST http://192.0.2.10:9430/insert/jsonline \
  -H 'Content-Type: application/json' \
  -d '{"_msg":"hello","app":"demo"}'
curl -s 'http://192.0.2.10:9431/select/logsql/query?query=app:demo&limit=10'

Content-Type: application/json is required. Without it the endpoint can return 200 while silently dropping the payload.

Destroy

Set each entry’s state in the group file to absent and re-run the same command. Data is removed with the member unless the entry sets clean_data: false; for SeaweedFS this includes the rendered s3.json and filer.toml. With serial: 1, members are removed one host at a time.

Dependency order:

  • etcd is the RabbitMQ coordination backend and the HA DCS. Remove RabbitMQ (and any Patroni cluster) before etcd.
  • clickhouse-keeper must outlive its ClickHouse members. Remove ClickHouse first, then Keeper.
  • The controller-side material in var/addon_cluster/shared/ survives a destroy/create cycle. To rotate passwords, remove that directory while every member is absent; existing members keep their old passwords and must be recreated. RabbitMQ secrets live in etcd, so they disappear with the etcd data and are regenerated on the next RabbitMQ run.

Removing an add-on does not touch the shared TLS files on the members, so a recreate can reuse them.

12 - HA clusters

Configure the ha_etcd and ha_cluster example files — shared etcd DCS, Patroni clusters, HAProxy, and state-driven destroy

The HA deployment spans two inventory groups and two example variable files:

Group File Role
[ha_etcd] group_vars/ha_etcd/main.yml Shared etcd DCS, one member per host
[ha_cluster] group_vars/ha_cluster/main.yml Patroni members, per-namespace clusters, HAProxy

The same hosts may appear in both groups (co-located layout). List the etcd bootstrap host first; the add-on play is serial.

etcd: group_vars/ha_etcd/main.yml.example

The file is group-name agnostic: set pg_etcd_group once and everything below follows it.

pg_etcd_group: ha_etcd

_ha_etcd_advertise_host: "{{ private_ip | default(ansible_host, true) }}"
_ha_etcd_client_endpoint: "{{ _ha_etcd_advertise_host }}:2379"
_ha_etcd_bootstrap_endpoint: "http://{{ hostvars[groups[pg_etcd_group] | first].private_ip | default(...) }}:2379"

pgcli_addons:
  - type: etcd
    name: "etcd-{{ groups[pg_etcd_group].index(inventory_hostname) + 1 }}"
    state: present
    autostart: true
    args: "{{ ['--cluster', 'ha', '--advertise-host', _ha_etcd_advertise_host]
             + (['--join', _ha_etcd_bootstrap_endpoint]
                if inventory_hostname != (groups[pg_etcd_group] | first) else []) }}"

_ha_etcd_client_endpoint is consumed by ha_cluster to build the Patroni DCS endpoint list. Setting the entry’s state: absent destroys the group (remove the Patroni clusters first).

Patroni: group_vars/ha_cluster/main.yml.example

The host default config gets a namespace, and extra namespaces are declared with their own directories and port ranges:

pgcli_config_overrides:
  namespace: ha

pgcli_namespaces:
  - name: ha
    path: /root/.pgcli
  - name: ha2
    path: /root/.pgcli/ha2
    base_dir: /data/pg-ha2
    backup_dir: /mnt/backup/pg-ha2
    pg_start_port: 36432
    pg_ssh_port: 43201

Which etcd group supplies the DCS, and the derived endpoint list:

pg_ha_etcd_group: ha_etcd
_ha_dcs_endpoints: >-
  {{ groups[pg_ha_etcd_group]
     | map('extract', hostvars, '_ha_etcd_client_endpoint') | list }}

Shared S3 backup repository (secret key lives in secrets.yaml):

pgcli_backup_s3_host: s3-01
pgcli_backup_s3_port: 19800
pgcli_backup_s3_bucket: pgbackup
pgcli_backup_s3_access_key: admin

One cluster entry per namespace:

pg_ha_clusters:
  - namespace: ha
    scope: pgcluster
    members: [ha1, ha2, ha3]
    host_port: 35532
    restapi_port: 8008
    dcs_endpoints: "{{ _ha_dcs_endpoints }}"
    state: started          # started | stopped | absent
    autostart: true
    extensions:
      - pg_stat_statements
Field Meaning
namespace Namespace from pgcli_namespaces
scope Patroni scope; the namespace suffix keeps clusters apart in DCS
members One name per [ha_cluster] host, in inventory order
host_port, restapi_port PostgreSQL and Patroni REST ports; disjoint per cluster
dcs_endpoints etcd client endpoints
state started (default), stopped, absent
clean_data With absent: delete member data dirs
autostart Enable boot autostart for the members
extensions Extensions installed cluster-wide

Port ranges, data dirs and backup dirs must not overlap between namespaces. The same scope name in two namespaces is safe: pgcli bakes the namespace suffix into the DCS scope and container names.

HAProxy

pg_ha_haproxy_host: "{{ groups['ha_cluster'] | first }}"
pg_ha_haproxy:
  enabled: true
  mode: split          # rw/ro listeners
  max_lag: 1MB
  listen: 0.0.0.0
  autostart: true      # default for all entries; override per cluster
  clusters:
    - namespace: ha
      name: lb-ha
      rw_port: 5000
      ro_port: 5001
      stats_port: 5002
      state: present    # present (default) | absent

The proxy targets every [ha_cluster] member via --node; run it on a host that carries the namespace config. Both instances share one host network, so their ports must differ. autostart reconciles pg autostart enable|disable --haproxy --name <name> per instance; it defaults to false when unset.

Run it

# etcd + Patroni + HAProxy in one pass
uv run ansible-playbook playbooks/apply.yaml --tags addon,ha

# Reconcile the clusters and proxies only (etcd must already exist)
uv run ansible-playbook playbooks/apply.yaml --tags ha

# HAProxy only
uv run ansible-playbook playbooks/apply.yaml --tags haproxy

# Read-only topology and proxy status
uv run ansible-playbook playbooks/ha-status.yaml

Destroy order

The state switches are independent; destroy in dependency order:

  1. HAProxy: set pg_ha_haproxy.clusters[].state: absent, run --tags haproxy.
  2. Patroni clusters: set pg_ha_clusters[].state: absent (add clean_data: true to delete member data dirs), run --tags ha.
  3. etcd: set state: absent on the etcd entry in group_vars/ha_etcd, run --tags addon.

The HA plays clear the DCS scope on the first host and remove each host’s local members serially; later hosts are a no-op for the scope. clean_data deletes the member data dirs but leaves the empty addon/patroni/<scope> directory. etcd removal always deletes its data dir. Backup containers, the pgBackRest configuration and S3 backups are left intact by all of the above.

13 - S3 storage

Deploy a standalone MinIO, silo or rustfs store with deploy-s3.yaml and use it as the pgBackRest backup target

A standalone S3-compatible store gives backup_target: s3 instances and HA clusters a shared pgBackRest repository. Three store types are supported, each with its own example group.

Activate one store type

hosts.ini.example declares all three groups; only one child is active under [s3] at a time:

[silo_s3]
s3-01 ansible_host=192.0.2.20 private_ip=192.0.2.20 ansible_user=root ansible_port=22

[s3:children]
# minio_s3
silo_s3
# rustfs_s3

Copy the matching example group vars:

cp group_vars/silo_s3/main.yml.example group_vars/silo_s3/main.yml

group_vars/<type>_s3/main.yml.example

The example is commented per field; the commonly edited ones:

Variable Meaning
pgcli_s3_type minio, silo or rustfs; must agree with the group name
pgcli_s3_name Instance name (default backup)
pgcli_s3_api_port, pgcli_s3_console_port S3 API and web console ports
pgcli_s3_listen Bind address; TLS + network boundary guard the store
pgcli_s3_tls Serve HTTPS; pgBackRest refuses plaintext HTTP
pgcli_s3_autostart Start the store at boot; default true
pgcli_s3_root_user Root/access user
pgcli_s3_root_password Root secret; keep it in secrets.yaml for a grid
pgcli_s3_drives One directory per drive; empty uses pgcli_s3_data_dir
pgcli_s3_data_dir Single-node data directory
pgcli_s3_endpoints Override the derived endpoint matrix
pgcli_s3_tls_sans, pgcli_s3_cert_cn Extra SANs / certificate CN
pgcli_s3_tls_cert, pgcli_s3_tls_key Bring-your-own certificate pair
pgcli_s3_force Recreate the container
pgcli_s3_buckets Buckets to create after install

Layout is derived from hosts and drives

Hosts Drives Mode Flags per node
1 0 SNSD --data-dir
1 N SNMD --drive × N
>1 0 MNSD --data-dir + one --endpoint per node
>1 N MNMD --drive × N + one --endpoint per node per drive

The endpoint matrix is generated in inventory order from each host’s private_ip (falling back to ansible_host), so every node receives the same list. A multi-node grid needs one shared root password and a shared certificate; single-node stores generate their own CA. rustfs has no MNSD: multi-node requires --drive on every node.

Deploy

# Active store-type group
uv run ansible-playbook playbooks/deploy-s3.yaml

# Explicit type / subset of nodes / force
uv run ansible-playbook playbooks/deploy-s3.yaml -e pgcli_s3_group=minio_s3
uv run ansible-playbook playbooks/deploy-s3.yaml -e pgcli_s3_nodes=db-01
uv run ansible-playbook playbooks/deploy-s3.yaml -e pgcli_s3_force=true

Use the store as a backup target

In the database mode group (crosshost, ha_cluster, …), point at one store node:

pgcli_backup_s3_host: s3-01
pgcli_backup_s3_port: 9000
pgcli_backup_s3_bucket: pgbackup
pgcli_backup_s3_access_key: admin
# secret in secrets.yaml: pgcli_backup_s3_secret_key

Then set backup_target: s3 on the instance (fixed at creation time). For HA clusters, the pg_ha role consumes the same pgcli_backup_s3_* variables from group_vars/ha_cluster, as shown on the HA clusters page. The pg_instance role resolves <private_ip>:<port>, copies the store CA from <base>/tls/<type>/<name>/ca.crt, and runs pg backup setup before creating the instance.

For a store outside this inventory, omit pgcli_backup_s3_host, set pgcli_backup_s3_endpoint: host:port (no scheme), and the role falls back to pg backup fetch-ca.

Optional knobs: pgcli_backup_s3_region, _s3_path, _no_verify_tls, _ca_file, _ca_sha256 (see the mode example files).

Removal

deploy-s3.yaml is deploy-only. Destroy a store on its node with the product CLI:

pg addon remove <type> --name <name> --clean-data