This is the multi-page printable view of this section. .
Configuration
- 1: Cluster / Instance
- 2: Kernel Version
- 3: Package Alias
- 4: User/Role
- 5: Database
- 6: HBA Rules
- 7: Access Control
- 8: Parameters
Pigsty uses configuration to control PostgreSQL behavior.
This configuration combines inventory files in ~/pigsty/conf/*.yml with PGSQL parameters.
After you write the configuration, you can reproduce a customized cluster in a few minutes.
The configuration includes instances, users, databases, access control, extensions, and tuning policies.
Configuration Entry
- Prepare Inventory: Copy a
pigsty/conf/*.ymltemplate or write an Ansible inventory. Put cluster groups (all.children.<cls>.hosts) and global variables (all.vars) in the same file. - Define Parameters: Override the required
PGSQLparameters invars. The override order is global → cluster → host. The last applicable setting determines the value. - Apply Configuration: Use
./configure -c <conf>,bin/pgsql-add <cls>, and other playbooks to apply the configuration. Pigsty generates the required Patroni, PgBouncer, and pgBackRest files from these parameters.
The default demonstration inventory, conf/pgsql.yml, provides a minimal example.
It defines one pg-meta cluster, global pg_version: 18, and a few application users and databases.
You can add more clusters to this configuration.
Focus Areas & Documentation Index
Use the following pages to configure each part of a PostgreSQL deployment:
- Cluster & Instances: Define instance topology (standalone, primary-replica, standby cluster, delayed cluster, Citus, etc.) through
pg_cluster / pg_role / pg_seq / pg_upstream. - Kernel Version: Select the core version, flavor, and tuning templates using
pg_version,pg_mode,pg_packages,pg_extensions,pg_conf, and other parameters. - Users/Roles: Declare system roles, business accounts, password policies, and connection pool attributes in
pg_default_rolesandpg_users. - Database Objects: Create databases as needed using
pg_databases,baseline,schemas,extensions,pool_*fields and automatically integrate with pgbouncer/Grafana. - Access Control (HBA): Maintain host-based authentication policies using
pg_default_hba_rulesandpg_hba_rulesto ensure access boundaries for different roles/networks. - Privilege Model (ACL): Converge object privileges through
pg_default_privileges,pg_default_roles,pg_revoke_publicparameters, providing an out-of-the-box layered role system.
Use these parameters to declare infrastructure in the inventory for your application requirements. Pigsty performs the operations and ensures idempotency.
A Typical Example
This example defines topology, kernel version, extensions, users, and databases in one configuration file:
- The
pg-analyticscluster contains one primary and one offline replica. - Global settings specify
pg_version: 18with a set of extension examples and loadolap.ymltuning. - Declare business objects in
pg_databasesandpg_users, automatically generating schema/extension and connection pool entries. - Additional
pg_hba_rulesrestrict access sources and authentication methods.
Adjust and apply this inventory to create a customized PostgreSQL cluster without manual configuration.
1 - Cluster / Instance
Select instance and cluster types that meet your requirements.
Pigsty supports several PostgreSQL instance and cluster types:
- Primary: Define a single instance cluster.
- Replica: Define a basic HA cluster with one primary and one replica.
- Offline: Define an instance dedicated to OLAP/ETL/interactive queries
- Sync Standby: Enable synchronous commit to ensure no data loss.
- Quorum Commit: Use quorum sync commit for a higher consistency level.
- Standby Cluster: Clone an existing cluster and follow it
- Delayed Cluster: Clone an existing cluster for emergency data recovery
- Citus Cluster: Define a Citus distributed database cluster
Primary
The simplest cluster contains one primary instance:
This configuration contains only identity parameters.
Matching the Ansible group name to pg_cluster makes selectors such as -l pg-test convenient.
However, matching group names are not required for membership.
Pigsty finds members from each host’s pg_cluster identity.
One PostgreSQL cluster can therefore span multiple inventory groups.
Use the following command to create this cluster:
One instance can be suitable for demonstrations, development tests, temporary hosting, or non-critical analytical tasks. A single-node cluster has no high availability. After hardware failure, use PITR or another recovery method to meet RTO/RPO requirements. Consider adding read-only replicas for this reason.
Replica
To add a read-only replica, add a node to pg-test and set its pg_role to replica.
If the cluster does not exist, create the complete cluster. If the primary is initialized, add a replica to the existing cluster:
If the primary fails, the high-availability system can promote a replica to take over. Replicas also process read-only queries. Many applications have more reads than writes, so replicas can handle most of their read-only workload.
Offline
Offline instances are read-only replicas for slow queries, ETL, OLAP, and interactive queries. Slow queries and long transactions can reduce online application performance and stability. We therefore recommend that you isolate them from online traffic.
To add an offline instance, add a new instance and set pg_role to offline.
Dedicated offline instances operate like ordinary replicas but act as backup servers for the pg-test-replica service.
Offline and primary instances serve read-only traffic only when every replica instance is down.
A separate offline server may be too expensive when resources are limited.
Instead, mark an existing replica with pg_offline_query.
This replica handles both online read-only requests and offline queries.
Use pg_default_hba_rules and pg_hba_rules for additional access control on offline instances.
Sync Standby
With Sync Standby enabled, PostgreSQL selects one replica as the sync standby. The other replicas are candidates. Before it confirms a commit, the primary waits for the sync standby to flush data to disk. The sync standby has the latest data without replication lag. A switchover to that standby has no data loss.
PostgreSQL uses asynchronous streaming replication by default.
If the primary fails, WAL that has not replicated may be lost.
pg_rpo is Patroni’s sampled lag threshold for failover candidates.
It is not a hard limit on actual data loss.
The loss window also depends on write rate, replication state, and Patroni sampling time.
Critical workloads, such as financial transactions, may permit no data loss or read replication lag.
Use synchronous commit for these requirements.
To enable sync standby mode, select crit.yml with pg_conf.
To enable sync standby on an existing cluster, configure the cluster and enable synchronous_mode:
Patroni manages synchronous_standby_names automatically.
It selects one replica as the sync standby.
It writes and applies that replica’s application_name in the primary configuration.
Quorum Commit
Quorum Commit lets you set commit acknowledgment criteria, particularly for clusters with multiple replicas. You can adjust the consistency level and the associated availability tradeoff.
To require confirmation from at least two replicas, set synchronous_node_count through Patroni cluster configuration.
Apply this setting:
To require more synchronous replicas, increase synchronous_node_count.
After cluster size changes, verify that this setting remains valid to avoid service unavailability.
In this case, the PostgreSQL configuration parameter synchronous_standby_names is automatically managed by Patroni.
After applying the configuration, two sync standbys appear.
You can also require confirmation from any n replicas. For example, this configuration requires any one replica:
After applying, the configuration takes effect, and all standbys become regular replicas in Patroni. However, in pg_stat_replication, you can see sync_state becomes quorum.
Standby Cluster
You can clone an existing cluster and create a standby cluster for data migration, horizontal splitting, multi-region deployment, or disaster recovery.
Normally, the standby cluster follows the upstream cluster and keeps its data synchronized. Promote it to make it an independent cluster.
Use a normal cluster definition, then add pg_upstream to its primary.
This primary is called the Standby Leader.
This inventory defines pg-test and its standby cluster, pg-test2:
pg-test2-1 replicates from pg-test and acts as the Standby Leader for pg-test2.
Set pg_upstream on the standby cluster primary to pull backups automatically from the upstream cluster.
If necessary (e.g., upstream primary-standby switchover/failover), you can change the standby cluster’s replication upstream through cluster configuration.
To do this, simply change standby_cluster.host to the new upstream IP address and apply.
You can promote the standby cluster at any time. It then accepts writes independently and can diverge from the original cluster.
To do this, you must configure the cluster and completely erase the standby_cluster section, then apply.
If you specify pg_upstream on a replica instead of the primary, you can configure cascade replication for the cluster.
For cascade replication, use the IP address of an instance in the same cluster. Otherwise, initialization fails. The replica streams from that instance instead of the primary.
The WAL relay is called a Bridge Instance. It reduces the WAL transmission load on the primary. Consider cascade replication through bridge instances when you have dozens of replicas.
Delayed Cluster
A Delayed Cluster is a special type of standby cluster used to quickly recover “accidentally deleted” data.
For example, define pg-testdelay to retain the state of pg-test from one hour earlier:
You can also configure a “replication delay” on an existing standby cluster.
After accidental row or table deletion, adjust this delay to advance the delayed cluster to the required time. Read the data from that cluster to repair the original cluster.
Delayed clusters need additional resources. They recover data much faster than PITR and have less effect on the system. Consider them for critical clusters.
Citus Cluster
Pigsty natively supports Citus.
See conf/ha/citus.yml for a complete example.
To define a Citus cluster, you need to specify the following parameters:
pg_modemust be set tocitus, not the defaultpgsql- The shard name
pg_shardand shard numberpg_groupmust be defined on each shard cluster pg_primary_dbmust be defined to specify the database managed by Patroni.- To run administration commands as
pg_dbsupostgresinstead ofpg_admin_username, setpg_dbsu_passwordto a non-empty plaintext password.
Add HBA rules for SSL access from localhost and other data nodes. For example:
On the coordinator, create distributed tables and reference tables. You can query them from any data node. From Citus 11.2, any Citus database node can act as coordinator.
2 - Kernel Version
Choosing a “kernel” in Pigsty means determining the PostgreSQL major version, mode/distribution, packages to install, and tuning templates to load.
The Pigsty v4.5 source supports PostgreSQL 14-18 and uses 18 by default. Use the following configuration settings to select a kernel.
Major Version and Packages
pg_version: Select the PostgreSQL major version. The default is 18. Pigsty maps the version to the correct package name prefix.pg_packages: Select core packages with package aliases. The default,pgsql-main pgsql-common, includes the kernel, Patroni, PgBouncer, pgBackRest, and other common tools.pg_extensions: Select additional extension packages. Aliases are supported. The default is empty, which installs only core dependencies.
During installation, Ansible downloads packages for
pg_version=18and installs extension files on the system. Database initialization scripts can then runCREATE EXTENSION.
Extension availability differs between versions in Pigsty’s offline repository.
PostgreSQL 14 has fewer extensions, while 17/18 have the widest coverage.
If an extension is not included, add it through repo_extra_packages.
Kernel Mode (pg_mode)
pg_mode selects the kernel distribution.
The default, pgsql, selects standard PostgreSQL.
Pigsty supports these modes:
| Mode | Scenario |
|---|---|
pgsql | Standard PostgreSQL, HA + replication |
citus | Citus distributed cluster, requires additional pg_shard / pg_group |
gpsql | Cloudberry / Greenplum / MatrixDB |
mssql | Babelfish |
mysql | OpenGauss/HaloDB compatible with MySQL protocol |
polar | Alibaba PolarDB (based on pg polar distribution) |
ivory | IvorySQL (Oracle-compatible syntax) |
pgtde | Percona PostgreSQL with pg_tde under /usr/pgtde-$v |
oriole | OrioleDB storage engine |
agens | AgensGraph graph database kernel |
pgedge | pgEdge distributed replication kernel |
pg_mode selects binary paths, Patroni integration, and some kernel-specific behavior.
It does not automatically add every required package, extension, and application database.
For deployment, use the matching conf/*.yml template.
Alternatively, set pg_packages, pg_extensions, pg_libs, and pg_databases explicitly.
This is a minimal Citus example:
conf/ha/citus.ymlprovides the current complete example. The example above explicitly installs Citus packages and creates the extension in thecitusdatabase.
Extensions and Pre-installed Objects
Use these parameters to control components loaded automatically after database startup:
pg_libs: List to write toshared_preload_libraries. For example:pg_libs: 'timescaledb, pg_stat_statements, auto_explain'.pg_default_extensions/pg_default_schemas: Control schemas and extensions pre-created intemplate1andpostgresby initialization scripts.pg_parameters: Rendered by Pigsty intopostgresql.auto.confduring configuration. Do not also manage the same settings manually withALTER SYSTEM.
Example: Enable TimescaleDB, pgvector and customize some system parameters.
During initialization, Pigsty creates default extensions in
template1andpostgres. New databases based ontemplate1inherit these objects. Pigsty writespg_parametersdirectly topostgresql.auto.conf.
Tuning Template (pg_conf)
pg_conf selects a Patroni template from roles/pgsql/templates/*.yml.
Pigsty includes four general templates:
| Template | Applicable Scenario |
|---|---|
oltp.yml | Default template, for 4–128 core TP workload |
olap.yml | Optimized for analytical scenarios |
crit.yml | Emphasizes sync commit/minimal latency, suitable for zero-loss scenarios like finance |
tiny.yml | Lightweight machines / edge scenarios / resource-constrained environments |
You can replace the template or customize a YAML file in templates/.
Then select it in the cluster vars.
Pigsty uses
crit.ymlas the Patroni configuration and writespg_parametersoverrides topostgresql.auto.conf. The instances then use synchronous commit immediately.
Combined Instance: A Complete Example
- First primary + one replica, using
olap.ymltuning. - Install PG18 plus common RAG extensions; only libraries that actually require preloading belong in
pg_libs. - Patroni/pgbouncer/pgbackrest generated by Pigsty, no manual intervention needed.
Adjust these parameters for the application requirements to customize the kernel configuration.
3 - Package Alias
PostgreSQL package names differ between operating systems:
- EL systems (RHEL/Rocky/Alma/…) use formats like
pgvector_18,postgis36_18* - Debian/Ubuntu systems use formats like
postgresql-18-pgvector,postgresql-18-postgis-3
Without aliases, you need different naming rules for each system. You must also include the correct PostgreSQL version in the names.
Package Alias
Use a Package Alias to specify the same component on different platforms. Pigsty converts it to the correct package names:
Alias Translation
An alias can also identify a group of packages.
For example, the default pg_packages value is:
Pigsty reads the alias list for the current operating system.
For el10.x86_64, it expands the aliases to PostgreSQL kernel, extension, and utility packages:
Then Pigsty substitutes the selected PostgreSQL major version into pgsql-main.
For example, with pg_version = 18:
This process lets you select functional components without specifying platform-specific package details.
Which Variables Can Use Aliases?
These four parameters accept package aliases. Pigsty converts the aliases to package names through the same process:
pg_extensions- PG extension packagespg_packages- PG kernel/base utility packagesrepo_packages- Package download parameter: packages to download to local repositoryrepo_extra_packages- Extension installation parameter: additional packages to download to local repository
Alias List
The Pigsty source directory roles/node_id/vars/ contains alias mappings for each operating system and architecture:
el10.x86_64el10.aarch64el9.x86_64el9.aarch64el8.x86_64el8.aarch64u26.x86_64u26.aarch64u24.x86_64u24.aarch64u22.x86_64u22.aarch64d13.x86_64d13.aarch64d12.x86_64d12.aarch64
How It Works
Alias Translation Process
Version Placeholder
The alias system uses $v as a PostgreSQL version placeholder.
Pigsty replaces each $v in an alias with the value of pg_version.
For example, when pg_version: 18:
| Alias Definition (EL) | Expanded Result |
|---|---|
postgresql$v* | postgresql18* |
pgvector_$v* | pgvector_18* |
timescaledb-tsl_$v* | timescaledb-tsl_18* |
| Alias Definition (Debian/Ubuntu) | Expanded Result |
|---|---|
postgresql-$v | postgresql-18 |
postgresql-$v-pgvector | postgresql-18-pgvector |
postgresql-$v-timescaledb-tsl | postgresql-18-timescaledb-tsl |
Wildcard Matching
On EL systems, many aliases use the * wildcard to match related subpackages.
For example:
postgis36_18*will matchpostgis36_18,postgis36_18-client,postgis36_18-utils, etc.postgresql18*will matchpostgresql18,postgresql18-server,postgresql18-libs,postgresql18-contrib, etc.
One alias can install a complete extension. You do not need to list each subpackage.
4 - User/Role
In this document, “user” refers to a logical object within a database cluster created with
CREATE USER/ROLE.
In PostgreSQL, users belong to the database cluster, rather than a specific database. Create business users before you create business databases.
Pigsty defines roles and users through two config parameters:
pg_default_roles: Define globally shared roles and userspg_users: Define business users and roles at cluster level
The first parameter defines roles and users shared across the environment. The second defines business roles and users for one cluster. Both parameters use arrays of user definition objects. Pigsty creates users and roles in array order. Thus, a later user can belong to an earlier role.
By default, all users marked with pgbouncer: true are added to the Pgbouncer connection pool user list.
Define Users
Example from Pigsty demo pg-meta cluster:
Each user or role definition is an object.
Only name is required:
User-level pool quota is consistently defined by
pool_connlimit(mapped to Pgbouncermax_user_connections).
Parameter Overview
The only required field is name.
It must be a valid username that is unique within the cluster.
All other parameters have defaults.
| Field | Category | Type | Attr | Description |
|---|---|---|---|---|
name | Basic | string | Required | Username, must be valid and unique |
state | Basic | enum | Optional | State: create (default), absent |
password | Basic | string | Mutable | User password, plaintext or hash |
comment | Basic | string | Mutable | User comment |
login | Privilege | bool | Mutable | Can login, default true |
superuser | Privilege | bool | Mutable | Is superuser, default false |
createdb | Privilege | bool | Mutable | Can create databases, default false |
createrole | Privilege | bool | Mutable | Can create roles, default false |
inherit | Privilege | bool | Mutable | Inherit role privileges, default true |
replication | Privilege | bool | Mutable | Can replicate, default false |
bypassrls | Privilege | bool | Mutable | Bypass RLS, default false |
connlimit | Privilege | int | Mutable | Connection limit, -1 unlimited |
expire_in | Validity | int | Mutable | Expire N days from now (priority) |
expire_at | Validity | string | Mutable | Expiration date, YYYY-MM-DD format |
roles | Role | array | Additive | Roles array, string or object format |
parameters | Params | object | Mutable | Role-level parameters |
pgbouncer | Pool | bool | Mutable | Add to connection pool, default false |
pool_mode | Pool | enum | Mutable | Pool mode: transaction (default) |
pool_connlimit | Pool | int | Mutable | Pool user max connections |
Parameter Details
name
This required string specifies the username. The username must be unique within the cluster.
Use a valid PostgreSQL identifier that matches ^[a-z_][a-z0-9_]{0,62}$.
Start with a lowercase letter or underscore.
Use only lowercase letters, digits, and underscores.
The maximum length is 63 characters.
state
Enum for user operation: create or absent. Default create.
| State | Description |
|---|---|
create | Default, create user, update if exists |
absent | Delete user with DROP ROLE |
Pigsty prevents deletion of these system users with state: absent to prevent cluster failure:
postgres: Database superuserreplicator: Replication user (orpg_replication_username)dbuser_dba: Admin user (orpg_admin_username)dbuser_monitor: Monitor user (orpg_monitor_username)
password
This mutable string specifies the user password. Users without a password cannot log in with password authentication.
Password can be:
| Format | Example | Description |
|---|---|---|
| Plaintext | DBUser.Meta | Not recommended, logged to config |
| SCRAM-SHA-256 | SCRAM-SHA-256$4096:xxx$yyy:zzz | Recommended, PG10+ default |
| MD5 hash | md5... | Legacy compatibility |
When Pigsty sets a password, it temporarily disables logging to prevent password disclosure:
To generate SCRAM-SHA-256 hash:
comment
String, mutable. User comment, defaults to business user {name}.
Pigsty sets the comment with COMMENT ON ROLE.
Special characters are supported, and Pigsty automatically escapes quotes.
login
This mutable Boolean controls login access.
The default is true.
Set false to create a Role rather than a user.
Roles usually group permissions.
In PostgreSQL, CREATE USER equals CREATE ROLE ... LOGIN.
superuser
This mutable Boolean controls superuser privileges.
The default is false.
Superusers have full database privileges. They bypass all permission checks.
Pigsty provides a default superuser through pg_admin_username (dbuser_dba).
Do not create additional superusers unless necessary.
createdb
This mutable Boolean controls permission to create databases.
The default is false.
Some applications, such as Gitea and Odoo, may require the CREATEDB privilege for their administration users.
createrole
This mutable Boolean controls permission to create other roles.
The default is false.
Users with CREATEROLE can create, modify, and delete other roles that are not superusers.
inherit
This mutable Boolean controls automatic inheritance of privileges from roles to which the user belongs.
The default is true.
If you set false, use an explicit SET ROLE command to use the role privileges.
replication
This mutable Boolean controls permission to start streaming replication.
The default is false.
Usually, only replication users (replicator) need this permission.
Regular users should not have it unless they need logical decoding subscriptions.
bypassrls
This mutable Boolean controls permission to bypass row-level security (RLS) policies.
The default is false.
When enabled, the user can access all rows, even when RLS policies apply. Usually, only administrators need this permission.
connlimit
This mutable integer sets the maximum number of concurrent connections.
The default is -1 (unlimited).
A positive integer limits the number of simultaneous sessions for this user. The limit does not apply to superusers.
expire_in
This mutable integer sets expiration to N days from the current date.
This parameter takes priority over expire_at.
Each playbook run recalculates the expiration date.
Use this parameter for temporary users that need periodic renewal.
Generates SQL:
expire_at
String, mutable. Expiration date in YYYY-MM-DD format, or special value infinity.
This parameter has lower priority than expire_in.
Use infinity for users that must not expire.
roles
This additive array lists the roles to which the user belongs. Array elements can be strings or objects.
Simple format - strings for role names:
Use objects for more detailed control:
Object Format Parameters:
| Param | Type | Description |
|---|---|---|
name | string | Role name (required) |
state | enum | grant (default) or absent/revoke: control membership |
admin | bool | true: WITH ADMIN OPTION, false: REVOKE ADMIN |
set | bool | PG16+: true: WITH SET TRUE, false: REVOKE SET |
inherit | bool | PG16+: true: WITH INHERIT TRUE, false: REVOKE INHERIT |
PostgreSQL 16+ New Features:
PostgreSQL 16 introduced finer-grained role membership control:
- ADMIN OPTION: Allow granting role to other users
- SET OPTION: Allow using
SET ROLEto switch to this role - INHERIT OPTION: Auto-inherit this role’s privileges
The set and inherit options work only in PG16+.
Earlier versions ignore them and add warning comments.
parameters
This mutable object sets role-level configuration parameters with ALTER ROLE ... SET.
The parameters apply to all sessions for this user.
Use the special value DEFAULT to reset a parameter to its PostgreSQL default.
This value is case-insensitive:
Common role-level params:
| Parameter | Description | Example |
|---|---|---|
work_mem | Query work memory | '64MB' |
statement_timeout | Statement timeout | '30s' |
lock_timeout | Lock wait timeout | '10s' |
idle_in_transaction_session_timeout | Idle transaction timeout | '10min' |
search_path | Schema search path | 'app,public' |
log_statement | Log level | 'ddl' |
temp_file_limit | Temp file size limit | '10GB' |
Query user-level parameters through the pg_db_role_setting system view.
pgbouncer
This mutable Boolean adds the user to the Pgbouncer user list.
The default is false.
For production users that need connection pool access, explicitly set pgbouncer: true.
The default, false, prevents accidental pool access for internal users.
Users with pgbouncer: true are added to /etc/pgbouncer/userlist.txt.
pool_mode
Enum, mutable. User-level pool mode: transaction, session, or statement. Default transaction.
| Mode | Description | Use Case |
|---|---|---|
transaction | Return connection after txn | Most OLTP apps, default |
session | Return connection after session | Apps needing session state |
statement | Return after each statement | Simple stateless queries |
User-level pool params are configured via /etc/pgbouncer/useropts.txt:
pool_connlimit
This mutable integer sets the maximum pool connections for the user.
If you omit it, Pigsty does not generate a user-level override.
The global pgbouncer.ini default of 100 then applies.
PgBouncer uses 0 for unlimited connections.
ACL System
Pigsty provides a built-in access control / ACL model. Assign these default business roles to users as required:
| Role | Privileges | Typical Use Case |
|---|---|---|
dbrole_readwrite | Global read-write | Primary application accounts |
dbrole_readonly | Global read-only | Read-only application access |
dbrole_admin | DDL privileges | Application administrators and table creation |
dbrole_offline | Independent read-only; instance scope controlled by HBA | Ad hoc users, ETL, and analytics |
dbrole_offline does not restrict a user to offline instances by itself.
To apply this restriction, set role: offline on the corresponding HBA rule.
See Offline Role and Instance Isolation.
To define your own ACL system, customize these parameters and templates:
pg_default_roles: System-wide roles and global userspg_default_privileges: Default privileges for new objectspg-init-roles.sql: Role creation SQL templatepg-init-template.sql: Privilege SQL template
Pgbouncer Users
Pigsty enables Pgbouncer as connection pool middleware by default.
Pigsty adds users from pg_users to the Pgbouncer user list only when they have pgbouncer: true.
Users in connection pool are listed in /etc/pgbouncer/userlist.txt:
User-level pool params are maintained in /etc/pgbouncer/useropts.txt:
When you create users, Pigsty reloads the Pgbouncer user list online. The reload does not affect existing connections.
Pgbouncer runs as the same dbsu as PostgreSQL.
The default is the postgres operating system user.
Use the pgb alias to access Pgbouncer administration functions.
Use pgbouncer_auth_query to query authentication data dynamically for pool users.
This parameter removes the need to manage pool users manually.
Related Resources
For user management operations, see User Management.
For user access privileges, see Access Control: Role System.
5 - Database
In this document, “database” refers to a logical object within a database cluster created with
CREATE DATABASE.
A PostgreSQL cluster can serve multiple databases at the same time. Define the required databases in the Pigsty cluster configuration.
Pigsty customizes the template1 database with default schemas, extensions, and privileges.
New databases inherit these settings from template1.
Use template to select another template for instant database cloning.
By default, Pigsty adds each application database to the PgBouncer connection pool with a 1:1 mapping.
pg_exporter discovers application databases automatically to monitor their objects.
Pigsty also registers all databases as PostgreSQL data sources in Grafana on every INFRA node for PGCAT dashboards.
Define Database
Define application databases in pg_databases, an array of database definition objects.
During cluster initialization, Pigsty creates databases in definition order.
A later database can therefore use an earlier database as a template.
Example from Pigsty demo pg-meta cluster:
Each database definition has the fields below.
Only name is required:
From Pigsty
v4.1.0, usepool_reserveandpool_connlimitfor database pools. These unify the legacy aliasespool_size_reserve/pool_max_db_conn.
Parameter Overview
Only name is required.
It must be a valid database name that is unique within the cluster.
All other parameters have defaults.
Immutable parameters take effect only at creation.
To change them, recreate the database.
| Field | Category | Type | Attr | Description |
|---|---|---|---|---|
name | Basic | string | Required | Database name, must be valid and unique |
state | Basic | enum | Optional | State: create (default), absent, recreate |
owner | Basic | string | Mutable | Database owner, defaults to postgres |
comment | Basic | string | Mutable | Database comment |
template | Template | string | Immutable | Template database, default template1 |
strategy | Template | enum | Immutable | Clone strategy: FILE_COPY or WAL_LOG (PG15+) |
encoding | Encoding | string | Immutable | Character encoding, default inherited (UTF8) |
locale | Encoding | string | Immutable | Locale setting, default inherited (C) |
lc_collate | Encoding | string | Immutable | Collation rule, default inherited (C) |
lc_ctype | Encoding | string | Immutable | Character classification, default inherited (C) |
locale_provider | Encoding | enum | Immutable | Locale provider: libc, icu, builtin (PG15+) |
icu_locale | Encoding | string | Immutable | ICU locale rules (PG15+) |
icu_rules | Encoding | string | Immutable | ICU collation customization (PG16+) |
builtin_locale | Encoding | string | Immutable | Builtin locale rules (PG17+) |
tablespace | Storage | string | Mutable | Default tablespace, change triggers data migration |
is_template | Privilege | bool | Mutable | Mark as template database |
allowconn | Privilege | bool | Mutable | Allow connections, default true |
revokeconn | Privilege | bool | Mutable | Revoke PUBLIC CONNECT privilege |
connlimit | Privilege | int | Mutable | Connection limit, -1 for unlimited |
baseline | Init | string | Mutable | SQL baseline file path, runs on every provisioning |
schemas | Init | (string|object)[] | Mutable | Schema definitions to create |
extensions | Init | (string|object)[] | Mutable | Extension definitions to install |
parameters | Init | object | Mutable | Database-level parameters |
pgbouncer | Pool | bool | Mutable | Add to connection pool, default true |
pool_mode | Pool | enum | Mutable | Pool mode: transaction (default) |
pool_size | Pool | int | Mutable | Default pool size, default 50 |
pool_size_min | Pool | int | Mutable | Min pool size, default 0 |
pool_reserve | Pool | int | Mutable | Reserve pool size, default 30 |
pool_connlimit | Pool | int | Mutable | Max database connections, default 100 |
pool_auth_user | Pool | string | Mutable | Auth query user |
register_datasource | Monitor | bool | Mutable | Register to Grafana datasource, default true |
Parameter Details
name
String, required. Database name - must be unique within the cluster.
The current role does not enforce this regular expression.
It double-quotes SQL identifiers, but also uses the name in temporary paths and shell/SQL commands.
For safe operation throughout the automation, keep the name within 63 bytes and follow ^[A-Za-z_][A-Za-z0-9_$]{0,62}$.
Avoid spaces, quotes, slashes, and other special characters.
state
Enum for database operation: create, absent, or recreate. Default create.
| State | Description |
|---|---|
create | Default, create or modify database, adjust mutable params if exists |
absent | Delete database with DROP DATABASE WITH (FORCE) |
recreate | Drop then create, for database reset |
owner
String. Database owner, defaults to pg_dbsu (postgres) if not specified.
The target user must exist. To change the owner, Pigsty runs the following commands. The old owner retains existing privileges.
The database owner has full control, including schema, table, and extension creation. This is useful for multi-tenant deployments.
comment
String. Database comment, defaults to business database {name}.
Pigsty uses COMMENT ON DATABASE to set the comment.
Comments support Chinese and special characters; Pigsty escapes quotes automatically.
PostgreSQL stores them in pg_shdescription, the shared-object comment catalog.
Use \l+ to show them.
template
String, immutable. Template database for creation, default template1.
CREATE DATABASE clones the template, including objects, extensions, schemas, and permissions.
Pigsty customizes template1 during cluster initialization.
New databases inherit these settings.
| Template | Description |
|---|---|
template1 | Default, includes Pigsty pre-configured extensions/schemas/perms |
template0 | Clean template, required for non-default locale providers |
| Custom database | Use existing database as template for cloning |
For the icu or builtin locale provider, specify template: template0.
You cannot override the locale settings inherited from template1.
template0 omits the monitoring extensions, schemas, and default privileges.
Use it for a fully custom database.
strategy
Enum, immutable. Clone strategy: FILE_COPY or WAL_LOG. Available PG15+.
| Strategy | Description | Use Case |
|---|---|---|
FILE_COPY | Direct file copy with checkpoints before and after | Large templates, lower WAL volume |
WAL_LOG | Block-by-block copy written to WAL; PG15+ default | Small templates, non-blocking |
WAL_LOG permits template connections during cloning but is less efficient for large templates.
PG14 and earlier ignore this setting.
encoding
String, immutable. Character encoding, inherits from template if unspecified (usually UTF8).
We strongly recommend UTF8 unless you have special requirements.
You cannot change the encoding after creation.
locale
String, immutable. Locale setting - sets both lc_collate and lc_ctype. Inherits from template (usually C).
This setting controls string sort order and character classification.
Use C or POSIX for the best performance and cross-platform consistency.
For language-specific sorting, use a locale such as zh_CN.UTF-8.
lc_collate
String, immutable. String collation rule. Inherits from template (usually C).
This setting controls ORDER BY and comparison results.
Common values are C (byte order, fastest), C.UTF-8, en_US.UTF-8, and zh_CN.UTF-8.
You cannot change it after creation.
lc_ctype
String, immutable. Character classification rule for upper/lower case, digits, letters. Inherits from template (usually C).
This setting affects upper(), lower(), regex \w, and similar operations.
You cannot change it after creation.
locale_provider
Enum, immutable. Locale implementation provider: libc, icu, or builtin. Available PG15+, default libc.
| Provider | Version | Description |
|---|---|---|
libc | - | OS C library, traditional default, varies by system |
icu | PG15+ | ICU library, cross-platform consistent, more langs |
builtin | PG17+ | PostgreSQL builtin, most efficient, C/C.UTF-8 only |
For icu or builtin, use template: template0.
Also set the corresponding icu_locale or builtin_locale.
icu_locale
String, immutable. ICU locale identifier. Available PG15+ when locale_provider: icu.
ICU identifiers follow BCP 47. Common values:
| Value | Description |
|---|---|
en-US | US English |
en-GB | British English |
zh-Hans | Simplified Chinese |
zh-Hant | Traditional Chinese |
ja-JP | Japanese |
ko-KR | Korean |
icu_rules
String, immutable. Custom ICU collation rules. Available PG16+.
Use ICU Collation Customization to adjust the default sort behavior.
builtin_locale
String, immutable. Builtin locale provider rules. Available PG17+ when locale_provider: builtin. Values: C or C.UTF-8.
PG17 introduced the builtin provider.
It is faster than libc and provides consistent behavior across platforms.
It supports only C/C.UTF-8 collation.
tablespace
String, mutable. Default tablespace, default pg_default.
Changing the tablespace moves all database objects to the new tablespace. For large databases, this physical migration can take a long time. Use it carefully.
is_template
Boolean, mutable. Mark database as template, default false.
If true, any user with CREATEDB can clone this database as a template.
Template databases usually contain predefined schemas, extensions, and data.
Before it deletes an is_template: true database, Pigsty runs ALTER DATABASE ... IS_TEMPLATE false.
allowconn
Boolean, mutable. Allow connections, default true.
If false, the database rejects all connections, including superuser connections.
Use this setting for maintenance or archival.
revokeconn
Boolean, mutable. Revoke PUBLIC CONNECT privilege, default false.
When true, Pigsty executes:
- Revoke PUBLIC CONNECT, regular users can’t connect
- Grant connect to replication user (
replicator) and monitor user (dbuser_monitor) - Grant connect to admin user (
dbuser_dba) and owner withWITH GRANT OPTION
Setting false restores PUBLIC CONNECT privilege.
connlimit
Integer, mutable. Max concurrent connections, default -1 (unlimited).
A positive integer limits simultaneous sessions. The limit does not apply to superusers.
baseline
String. SQL baseline file path executed while provisioning the database.
Baseline files usually contain schema definitions, initial data, and stored procedures.
The path is relative to the Ansible search path, usually files/.
If baseline is defined, the role runs that file on every provisioning pass for the database.
It runs even if the database already exists, and after state: recreate.
Make the SQL idempotent, or do not rerun it against an existing database.
schemas
Array, mutable (add/remove). Schema definitions to create or drop. Elements can be strings or objects.
Simple format - strings for schema names (create only):
Full format - objects for owner and drop operations:
Creation uses IF NOT EXISTS.
Deletion uses CASCADE, which deletes all objects in the schema.
extensions
Array, mutable (add/remove). Extension definitions to install or uninstall. Elements can be strings or objects.
Simple format - strings for extension names (install only):
Full format - objects for schema, version, and uninstall:
Installation uses IF NOT EXISTS ... CASCADE.
If an extension exists, PostgreSQL reports a NOTICE and skips it.
When possible, PostgreSQL installs dependencies automatically.
Uninstallation uses CASCADE and deletes dependent objects.
parameters
Object, mutable. Database-level config params via ALTER DATABASE ... SET. Applies to all sessions connecting to this database.
Use special value DEFAULT (case-insensitive) to reset to PostgreSQL default:
pgbouncer
Boolean, mutable. Add database to Pgbouncer pool list, default true.
If false, PgBouncer excludes the database and clients cannot access it through the connection pool.
Use this for internal management databases or direct connections.
pool_mode
Enum, mutable. Pgbouncer pool mode: transaction, session, or statement. Default transaction.
| Mode | Description | Use Case |
|---|---|---|
transaction | Return connection after txn | Most OLTP apps, default |
session | Return connection after session | Apps needing session state |
statement | Return after each statement | Simple stateless queries |
pool_size
Integer, mutable. Pgbouncer default pool size, default 50.
The pool size limits regular backend connections for this database pool.
pool_size_min controls prewarmed connections.
Adjust these values for the workload.
pool_size_min
Integer, mutable. Pgbouncer minimum pool size, default 0.
A value > 0 creates that number of backend connections in advance. This reduces latency for the first request.
pool_reserve
Integer, mutable. Pgbouncer reserve pool size, default 30.
If the default pool is full, PgBouncer can add up to pool_reserve connections for increased traffic.
pool_connlimit
Integer, mutable. Max connections via Pgbouncer pool, default 100.
This PgBouncer limit is independent of the database connlimit parameter.
pool_auth_user
String, mutable. User for Pgbouncer auth query.
Enable pgbouncer_auth_query to use this field.
If set, all PgBouncer connections to this database use the specified user for auth-query password verification.
register_datasource
Boolean, mutable. Register database to Grafana as PostgreSQL datasource, default true.
Set false to skip Grafana registration.
Use this for temporary, test, or internal databases that do not need monitoring.
Template Inheritance
If you do not set them explicitly, many parameters inherit from the template database.
The default template is template1.
Cluster initialization parameters determine its encoding settings:
| Cluster Param | Default | Description |
|---|---|---|
pg_encoding | UTF8 | Cluster encoding |
pg_locale | C / C-UTF-8 (if supported) | Cluster locale |
pg_lc_collate | C / C-UTF-8 (if supported) | Cluster collation |
pg_lc_ctype | C / C-UTF-8 (if supported) | Cluster ctype |
Unless you select another template, new databases clone template1.
PG_PROVISION customizes it with extensions, schemas, and default privileges.
Deep Customization
Use these parameters to customize the template database:
pg_default_roles: Default predefined roles and system userspg_default_privileges: Default privileges for objects created by admin userpg_default_schemas: Default schemas to createpg_default_extensions: Default extensions to createpg_default_hba_rules: Default PostgreSQL HBA rulespgb_default_hba_rules: Default Pgbouncer HBA rules
If these parameters are insufficient, use pg_init to specify custom cluster initialization scripts:
pg-init: Cluster init scriptpg-init-template.sql: Template customization SQLpg-init-roles.sql: Default roles SQL
Locale Providers
PostgreSQL 15+ introduced locale_provider to select the locale implementation.
You cannot change it after database creation.
The Pigsty configure wizard selects the builtin C.UTF-8/C locale provider from the PostgreSQL and OS versions.
Databases inherit the cluster locale by default.
To select a different provider, use template0.
Using ICU provider (PG15+):
Using builtin provider (PG17+):
Provider comparison: libc (traditional, OS-dependent), icu (PG15+, cross-platform, feature-rich), builtin (PG17+, most efficient C/C.UTF-8).
Connection Pool
PgBouncer improves short-connection performance and reduces contention. It prevents excessive connections from overwhelming the database and provides flexibility during migrations.
Pigsty configures one connection pool for each PostgreSQL instance.
It runs as pg_dbsu, which defaults to the postgres OS user.
The pool connects to PostgreSQL through the /var/run/postgresql Unix socket.
Pigsty adds all databases in pg_databases to pgbouncer by default.
Set pgbouncer: false to exclude specific databases.
Pgbouncer database list and config params are defined in /etc/pgbouncer/database.txt:
When you create databases, Pigsty reloads the PgBouncer database list online. Existing connections remain active.
6 - HBA Rules
Overview
HBA (Host-Based Authentication) controls who can connect to a database, from which source, and with which authentication method.
For the authentication model and default rules, see Authentication.
Pigsty manages HBA rules through pg_default_hba_rules and pg_hba_rules.
Pigsty generates these files during cluster initialization or HBA refresh:
| Config File | Path | Description |
|---|---|---|
| PostgreSQL HBA | /pg/data/pg_hba.conf | PostgreSQL server HBA rules |
| PgBouncer HBA | /etc/pgbouncer/pgb_hba.conf | Connection pool HBA rules |
HBA rules are controlled by these parameters:
| Parameter | Level | Description |
|---|---|---|
pg_default_hba_rules | G | PostgreSQL global default HBA |
pg_hba_rules | G/C/I | PostgreSQL cluster/instance add |
pgb_default_hba_rules | G | PgBouncer global default HBA |
pgb_hba_rules | G/C/I | PgBouncer cluster/instance add |
Rule features:
- Role filtering: Rules support
rolefield, auto-filter based on instance’spg_role - Order sorting: Rules support
orderfield, controls position in final config file - Two syntaxes: Supports alias form (simplified) and raw form (direct HBA text)
Refresh HBA
After you change the inventory, generate the configuration files again and reload the services:
Script executes the following playbook:
PostgreSQL only: ./pgsql.yml -l <cls> -t pg_hba,pg_reload -e pg_reload=true
PgBouncer only: ./pgsql.yml -l <cls> -t pgbouncer_hba,pgbouncer_reload
Do not edit /pg/data/pg_hba.conf or /etc/pgbouncer/pgb_hba.conf directly.
The next playbook run will overwrite these files.
Make changes in pigsty.yml, then run bin/pgsql-hba to refresh them.
Parameter Details
pg_default_hba_rules
This global PostgreSQL HBA rule list provides base access control for all clusters.
It is usually defined in all.vars.
- Type:
rule[], Level: Global (G)
pg_hba_rules
This list adds PostgreSQL HBA rules.
You can override it at cluster or instance level.
Pigsty merges it with the default rules and sorts the result by order.
- Type:
rule[], Level: Global/Cluster/Instance (G/C/I), Default:[]
pgb_default_hba_rules
This is the global default PgBouncer HBA rule list.
It is usually defined in all.vars.
- Type:
rule[], Level: Global (G)
pgb_hba_rules
PgBouncer cluster/instance-level additional HBA rules.
- Type:
rule[], Level: Global/Cluster/Instance (G/C/I), Default:[]
Note: PgBouncer HBA does not support
db: replication.
Rule Fields
Each HBA rule is a YAML dict supporting these fields:
| Field | Type | Required | Default | Description |
|---|---|---|---|---|
user | string | No | all | Username, supports all, placeholders, +rolename |
db | string | No | all | Database name, supports all, replication, db name |
addr | string | Yes* | - | Address alias or CIDR, see Address Aliases |
auth | string | No | pwd | Auth method alias, see Auth Methods |
title | string | No | - | Rule description, rendered as comment in config |
role | string | No | common | Instance role filter, see Role Filtering |
order | int | No | 1000 | Sort weight, lower first, see Order Sorting |
rules | list | Yes* | - | Raw HBA text lines, mutually exclusive with addr |
Either
addrorrulesmust be specified. Userulesto write raw HBA format directly.
Address Aliases
Pigsty provides address aliases to simplify HBA rule writing:
| Alias | Expands To | Description |
|---|---|---|
local | Unix socket | Local Unix socket |
localhost | Unix socket + 127.0.0.1/32 + ::1/128 | Loopback addresses |
admin | ${admin_ip}/32 | Admin IP address |
infra | All infra group node IPs | Infrastructure nodes |
cluster | All current cluster member IPs | Same cluster instances |
intra / intranet | 10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16 | Intranet CIDRs |
world / all | 0.0.0.0/0 + ::/0 | Any address (IPv4 + IPv6) |
<CIDR> | Direct use | e.g., 192.168.1.0/24 |
Intranet CIDRs can be customized via node_firewall_intranet:
Auth Methods
Pigsty provides auth method aliases for simplified config:
| Alias | Actual Method | Connection Type | Description |
|---|---|---|---|
pwd | scram-sha-256 or md5 | host | Auto-select based on pg_pwd_enc |
ssl | scram-sha-256 or md5 | hostssl | Force SSL + password |
ssl-sha | scram-sha-256 | hostssl | Force SSL + SCRAM-SHA-256 |
ssl-md5 | md5 | hostssl | Force SSL + MD5 |
cert | cert | hostssl | Client certificate auth |
trust | trust | host | Unconditional trust (dangerous) |
deny / reject | reject | host | Reject connection |
ident | ident | host | OS user mapping (PostgreSQL) |
peer | peer | local | OS user mapping (PgBouncer/local) |
pg_pwd_encdefaults toscram-sha-256. For legacy client compatibility, you can set it tomd5.
User Variables
During configuration generation, Pigsty replaces these user placeholders with the actual usernames:
| Placeholder | Default | Corresponding Param |
|---|---|---|
${dbsu} | postgres | pg_dbsu |
${repl} | replicator | pg_replication_username |
${monitor} | dbuser_monitor | pg_monitor_username |
${admin} | dbuser_dba | pg_admin_username |
Role Filtering
The role field in HBA rules controls which instances the rule applies to:
| Role | Description |
|---|---|
common | Default, applies to all instances |
primary | Primary instance only |
replica | Replica instance only |
offline | Offline instance only (pg_role: offline or pg_offline_query: true) |
standby | Standby instance |
delayed | Delayed replica instance |
Role filtering uses the instance pg_role variable.
Pigsty comments out non-matching rules with the prefix #.
Order Sorting
PostgreSQL uses the first matching HBA rule.
Rule order therefore affects authentication.
Pigsty uses order to sort the generated rules.
Order Interval Convention
| Interval | Usage |
|---|---|
0 - 99 | User high-priority rules (before all defaults) |
100 - 650 | Default rule zone (spaced by 50 for insertion) |
1000+ | User rule default (rules without order) |
PostgreSQL Default Rules Order
| Order | Rule Description |
|---|---|
| 100 | dbsu local ident |
| 150 | dbsu replication local |
| 200 | replicator localhost |
| 250 | replicator intra replication |
| 300 | replicator intra postgres |
| 350 | monitor localhost |
| 400 | monitor infra |
| 450 | admin infra ssl |
| 500 | admin world ssl |
| 550 | dbrole_readonly localhost |
| 600 | dbrole_readonly intra |
| 650 | dbrole_offline intra |
PgBouncer Default Rules Order
| Order | Rule Description |
|---|---|
| 100 | dbsu local peer |
| 150 | all localhost pwd |
| 200 | monitor pgbouncer intra |
| 250 | monitor world deny |
| 300 | admin intra pwd |
| 350 | admin world deny |
| 400 | all intra pwd |
Syntax Examples
Alias Form: Using Pigsty simplified syntax
Rendered result:
Raw Form: Using PostgreSQL HBA syntax directly
Rendered result:
Common Scenarios
Blacklist IP: Use order: 0 to ensure first match
Whitelist App Server: High priority for specific IP
Admin Force Certificate: Override default SSL password auth
Offline Instance Dedicated Network: Only on offline instances
Restrict Access by Database: Sensitive databases limited to specific networks
PgBouncer Dedicated Rules: Note no db: replication support
Complete Cluster Example
Verification & Troubleshooting
View Current HBA Rules
Test Connection Auth
Common Issues
| Error Message | Possible Cause | Solution |
|---|---|---|
no pg_hba.conf entry for host... | No matching HBA rule | Add corresponding rule and refresh |
password authentication failed | Wrong password or enc | Check password and pg_pwd_enc |
| Rule not taking effect | Not refreshed or order | Run bin/pgsql-hba, check order |
Important Notes
- Order sensitive: PostgreSQL HBA is first-match-wins, use
orderwisely - Role matching: Ensure
rolefield matches target instance’spg_role - Address format: CIDR must be correct, e.g.,
10.0.0.0/8not10.0.0.0/255.0.0.0 - PgBouncer limitation: Does not support
db: replication - TLS prerequisite:
sslandcertrequire server-side TLS; clients must still useverify-fullto authenticate the server - Test first: Validate in test environment before modifying HBA
- Refresh on scale: Rules using
addr: clusterneed refresh after cluster membership changes
Related Documentation
- HBA Management: Refresh, verification, and troubleshooting
- User Config: User and role configuration
- Access Control: Role system and permission model
- Authentication: HBA, SCRAM, client certificates, and default rules
- Encrypted Communication: TLS and server certificate verification
7 - Access Control
Access control combines roles, object privileges, database ACLs, and HBA. This page describes configuration parameters. For design and boundaries, see Access Control Concepts.
Pigsty provides a compact ACL model described by these parameters:
pg_default_roles: system roles and system users.pg_users: application users and roles.pg_default_privileges: default privileges on objects created by managed administrators and owners.pg_revoke_public,pg_default_schemas, andpg_default_extensions: default behavior fortemplate1.
Manage these parameters together with HBA and database definitions to produce reproducible access-control configuration.
Default Role System (pg_default_roles)
The defaults contain four business roles and four system users:
| Name | Type | Description |
|---|---|---|
dbrole_readonly | NOLOGIN | Shared read-only role with SELECT and USAGE |
dbrole_readwrite | NOLOGIN | Inherits read-only and adds INSERT, UPDATE, and DELETE |
dbrole_admin | NOLOGIN | Inherits pg_monitor and read-write; can create objects and triggers |
dbrole_offline | NOLOGIN | Independent read-only role; instance scope must be restricted explicitly through HBA |
postgres | User | System superuser; same name as pg_dbsu |
replicator | User | Streaming replication and backup; inherits monitoring and read-only privileges |
dbuser_dba | User | Primary administration account, also synchronized to PgBouncer |
dbuser_monitor | User | Monitoring account with pg_monitor; records slow SQL by default |
pg_default_roles contains these definitions as a complete list.
To customize it, copy and retain the required default roles and system users.
Then add new roles in dependency order.
If a role name changes, update its references in HBA, default privileges, and scripts.
Default Users and Credential Parameters
These parameters control system-user names and passwords:
| Parameter | Default | Purpose |
|---|---|---|
pg_dbsu | postgres | Database and OS superuser |
pg_dbsu_password | Empty string | dbsu password, disabled by default |
pg_replication_username | replicator | Replication user name |
pg_replication_password | DBUser.Replicator | Replication password |
pg_admin_username | dbuser_dba | Administrator user name |
pg_admin_password | DBUser.DBA | Administrator password |
pg_monitor_username | dbuser_monitor | Monitoring user |
pg_monitor_password | DBUser.Monitor | Monitoring password |
After changing these parameters, update the corresponding user definitions in pg_default_roles so user names and role attributes remain consistent.
Application Roles and Grants (pg_users)
Declare application users with pg_users.
The roles field grants application roles.
For field details, see User Configuration.
Example read-only and read-write users:
Application users inherit default object privileges through dbrole_*.
Database CONNECT privileges and pg_hba_rules also control which databases and sources can connect.
For more specific ACLs, use standard GRANT and REVOKE in baseline SQL or a later playbook.
Include these additional grants in reviews.
Default Privilege Template (pg_default_privileges)
pg_default_privileges applies to pg_dbsu, pg_admin_username, dbrole_admin, and every declared database owner.
The default template is:
Objects created by these identities receive the corresponding privileges automatically. Other object creators need their own
ALTER DEFAULT PRIVILEGESconfiguration.
Additional notes:
pg_revoke_publicdefaults totrue, revokingCREATEfromPUBLICon databases and thepublicschema.pg_default_schemasandpg_default_extensionscontrol schemas and extensions created intemplate1/postgres, usually for monitoring objects such as themonitorschema andpg_stat_statements.
Common Scenarios
Read-only Account for a Partner
This adds an HBA rule for partner access to analytics over TLS from the specified CIDR.
pg_hba_rules does not remove broader default rules.
If the account must access only this database, narrow the default HBA policy and configure database CONNECT privileges.
DDL for an Application Administrator
app_admininherits DDL privileges fromdbrole_admin. To apply thedbrole_admindefault privileges to new objects, first runSET ROLE dbrole_admin. Ifapp_adminis a declared database owner, it can create objects directly as that owner.
Custom Default Privileges
This parameter replaces the complete default privilege list. Referenced roles must already exist. Changes affect only objects created afterward. Grant privileges separately on existing objects.
Integration with Other Components
- HBA rules: use
pg_hba_rulesto bind roles, databases, and sources. To restrictdbrole_offline, setrole: offlineon its rule. - PgBouncer: users with
pgbouncer: trueare written touserlist.txt;pool_modeandpool_connlimitcontrol pool-level quotas. - Database monitoring:
dbuser_monitorreceives privileges frompg_default_roles. When adding another monitoring user, grantpg_monitorand check access to themonitorschema.
You can version these parameters with the inventory. Continue to review effective privileges through PostgreSQL catalogs.
Related Documentation
- Access Control Concepts: roles, default privileges, and isolation boundaries
- Authentication: HBA, SCRAM, and client certificates
- User Configuration: user and role fields
- HBA Configuration: connection-entry rules
8 - Parameters
You can set PostgreSQL parameters at several levels with different scopes and priorities. Pigsty supports four levels, from global to local:
| Level | Scope | Configuration Method | Storage Location |
|---|---|---|---|
| Cluster | All instances in cluster | Patroni DCS / Tuning Templates | etcd + postgresql.conf |
| Instance | Single PG instance | pg_parameters / ALTER SYSTEM | postgresql.auto.conf |
| Database | All sessions in a DB | pg_databases[].parameters | pg_db_role_setting |
| User | All sessions of a user | pg_users[].parameters | pg_db_role_setting |
Priority from low to high: Cluster < Instance < Database < User < Session (SET command).
Higher priority settings override lower ones.
For complete PostgreSQL parameter documentation, see PostgreSQL Docs: Server Configuration.
Cluster Level
Cluster-level parameters apply to every primary and replica in a PostgreSQL cluster. Pigsty manages them through Patroni and stores them in DCS, which is etcd by default.
Pigsty provides four Patroni tuning templates for different workloads.
Select one with pg_conf:
| Template | Use Case | Characteristics |
|---|---|---|
oltp.yml | OLTP transactions | Low latency, high concurrency (default) |
olap.yml | OLAP analytics | Large queries, high throughput |
crit.yml | Critical/Financial | Max durability, safety over perf |
tiny.yml | Tiny instances | Resource-constrained, dev/test |
Template files are in roles/pgsql/templates/.
They calculate parameter values from the hardware specifications.
During cluster initialization, Pigsty generates /etc/patroni/patroni.yml from the template.
See Tuning Templates.
Before cluster creation, adjust the templates to change initial parameters. After initialization, change parameters through Patroni configuration management.
Patroni DCS Config
Patroni stores cluster configuration in DCS, which is etcd by default. This keeps all members configured consistently.
Storage Structure:
Rendering Flow:
- Init: Template (e.g.,
oltp.yml) rendered via Jinja2 to/etc/patroni/patroni.yml - Start: Patroni reads local config, writes PostgreSQL parameters to DCS
- Runtime: Patroni periodically syncs DCS config to local PostgreSQL
Local Cache:
Each Patroni instance caches DCS config locally at /pg/conf/<instance>.yml:
- On start: Load from DCS, cache locally
- Runtime: Periodically sync DCS to local cache
- DCS unavailable: Continue with local cache (no failover possible)
Config File Hierarchy
Patroni renders DCS config to local PostgreSQL config files:
Load Order (priority low to high):
postgresql.conf: Dynamically generated by Patroni with DCS cluster paramspostgresql.base.conf: Loaded viainclude, static base configpostgresql.auto.conf: Auto-loaded by PostgreSQL, instance overrides
Since postgresql.auto.conf loads last, its parameters override earlier files.
Instance Level
Instance-level parameters apply to one PostgreSQL instance and override cluster-level configuration.
Pigsty writes them to postgresql.auto.conf.
This file loads last and can override any cluster parameter.
Use instance parameters for settings such as:
- Set
hot_standby_feedback = onon replicas - Adjust
work_memormaintenance_work_memfor specific instances - Set
recovery_min_apply_delayfor delayed replicas
Using pg_parameters
In Pigsty config, use pg_parameters to define instance-level parameters:
Run ./pgsql.yml -l <cls> -t pg_param to write these parameters to postgresql.auto.conf.
Override Hierarchy
pg_parameters can be defined at different Ansible config levels, priority low to high:
Using ALTER SYSTEM
You can also modify instance parameters at runtime via ALTER SYSTEM:
ALTER SYSTEM writes to postgresql.auto.conf.
Note: In Pigsty-managed clusters,
postgresql.auto.confis managed by Ansible viapg_parameters. ManualALTER SYSTEMchanges may be overwritten on next playbook run. Usepg_parametersinpigsty.ymlfor persistent instance-level params.
List-Type Parameters
Some PostgreSQL parameters accept comma-separated lists. In YAML, quote the entire value. Otherwise, YAML parses it as an array:
Pigsty auto-detects these list parameters and renders them without outer quotes:
| Parameter | Description | Example Value |
|---|---|---|
shared_preload_libraries | Preload shared libs | 'timescaledb, pg_stat_statements' |
search_path | Schema search path | '"$user", public, app' |
local_preload_libraries | Local preload libs | 'auto_explain' |
session_preload_libraries | Session preload libs | 'pg_hint_plan' |
log_destination | Log output targets | 'csvlog, stderr' |
unix_socket_directories | Unix socket dirs | '/var/run/postgresql, /tmp' |
temp_tablespaces | Temp tablespaces | 'ssd_space, hdd_space' |
debug_io_direct | Direct I/O mode (PG16+) | 'data, wal' |
Rendering Example:
Database Level
Database-level parameters apply to all sessions connected to a specific database.
ALTER DATABASE ... SET sets them in pg_db_role_setting.
Configuration
Use the parameters field in pg_databases:
Like instance-level params, list-type values must be quoted in YAML.
Rendering Rules
Pigsty sets database parameters with ALTER DATABASE ... SET.
It selects the required syntax automatically:
List-type params (search_path, temp_tablespaces, local_preload_libraries, session_preload_libraries, log_destination) without outer quotes:
Scalar params with quoted values:
Note:
log_destinationis in the database whitelist, but itscontextissighup. It cannot take effect at database level. Set it at instance level withpg_parameters.
View Database Params
Manual Management
User Level
User-level parameters apply to all sessions for a specific database user.
ALTER USER ... SET sets them in pg_db_role_setting.
Configuration
Use the parameters field in pg_users or pg_default_roles:
Rendering Rules
Same as database-level:
List-type params (search_path, temp_tablespaces, local_preload_libraries, session_preload_libraries) without outer quotes:
Scalar params with quoted values:
DEFAULT Value
Use DEFAULT (case-insensitive) to reset a parameter to PostgreSQL default:
View User Params
Manual Management
Priority
When the same parameter is set at multiple levels, PostgreSQL applies this priority (low to high):
Database vs User Priority:
If the same parameter is set for both the database and the connecting user, PostgreSQL uses the user-level parameter. The user setting has higher priority.
Example:
analystconnecting toanalytics:work_mem = 512MB(user takes precedence)- Other users connecting to
analytics:work_mem = 256MB(database applies) analystconnecting to other DBs:work_mem = 512MB(user applies)