Repository navigation
Expand file tree
/
Copy pathconfigure.sh
More file actions
515 lines (416 loc) · 13.8 KB
/
Copy pathconfigure.sh
File metadata and controls
515 lines (416 loc) · 13.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
#!/bin/bash
# ************************************************************************************
# Copyright (C) 2022-2026 rhctl Contributors
#
# SPDX-License-Identifier: Apache-2.0
# ************************************************************************************
# Configure installed PostgreSQL (listen, port, pg_hba, firewall)
# and ensure the service accepts connections.
#
# Does not create databases or roles — use db.sh --action create.
#
# Remote pg_hba access requires --allowed-ips; without it, only local
# 127.0.0.1 / ::1 TCP connections remain.
#
# Local administrative access always uses PostgreSQL peer authentication
# through the Unix socket.
#
# If exists, overwrite — safe to re-run.
#
# Usage:
# ./configure.sh --port 5432
# ./configure.sh \
# --port 5432 \
# --auth-method md5 \
# --allowed-ips 192.168.1.100,10.0.0.5
#
# Required Parameters:
# (none)
#
# Optional Parameters:
# --port <port>
# Listen port (default: `5432`).
# Example port values: `5432`, `5433`, `48985`
# --auth-method <method>
# pg_hba auth method for TCP connections (default: `md5`).
# Example method values: `md5`, `scram-sha-256`, `password`,
# `trust`, `reject`
# --allowed-ips <ip>[,<ip>...]
# Remote pg_hba allow-list.
# Re-runs overwrite prior remote host-all rules.
# When omitted, only local 127.0.0.1 / ::1 TCP rules remain.
# Example ip values: `192.168.1.100`, `10.0.0.5`,
# `192.168.1.0/24`, `0.0.0.0/0`, `::/0`
#
# Override Parameters:
# RHCTL_PG_PORT=<port>
# Same as `--port`.
# RHCTL_PG_AUTH_METHOD=<method>
# Same as `--auth-method`.
# RHCTL_PG_ALLOW_IPS=<ip>[,<ip>...]
# Same as `--allowed-ips`.
#
# Since : 1.0.3
# Date : Oct 6, 2026
# ************************************************************************************
set -euo pipefail
# ========================================================================= Parameter
RHCTL_PG_PORT="${RHCTL_PG_PORT:-5432}"
RHCTL_PG_AUTH_METHOD="${RHCTL_PG_AUTH_METHOD:-md5}"
NEED_RESTART=false
IPS=()
while [ "$#" -gt 0 ]; do
case "$1" in
--port)
if [ "$#" -lt 2 ]; then
echo "[ERROR] Missing value for --port"
exit 1
fi
RHCTL_PG_PORT="$2"
shift 2
;;
--auth-method)
if [ "$#" -lt 2 ]; then
echo "[ERROR] Missing value for --auth-method"
exit 1
fi
RHCTL_PG_AUTH_METHOD="$2"
shift 2
;;
--allowed-ips)
if [ "$#" -lt 2 ]; then
echo "[ERROR] Missing value for --allowed-ips"
exit 1
fi
IFS=',' read -r -a _parsed <<<"$2"
IPS+=("${_parsed[@]}")
shift 2
;;
-h|--help)
sed -n '2,61p' "$0"
exit 0
;;
--*)
echo "[ERROR] Unknown option: $1"
exit 1
;;
*)
IPS+=("$1")
shift
;;
esac
done
if [ "${#IPS[@]}" -eq 0 ] && [ -n "${RHCTL_PG_ALLOW_IPS:-}" ]; then
IFS=',' read -r -a IPS <<<"${RHCTL_PG_ALLOW_IPS}"
fi
case "$RHCTL_PG_AUTH_METHOD" in
md5|scram-sha-256|password|trust|reject)
;;
*)
echo "[ERROR] Unsupported --auth-method: ${RHCTL_PG_AUTH_METHOD}"
echo "[ERROR] Allowed: md5, scram-sha-256, password, trust, reject"
exit 1
;;
esac
# ========================================================================= Methods
log() {
echo "[INFO] $*"
}
warn() {
echo "[WARN] $*"
}
set_conf_kv() {
local key="$1"
local value="$2"
local file="$3"
local expected="${key} = ${value}"
local current
current=$(grep -E "^[[:space:]]*${key}[[:space:]]*=" "$file" | head -1 || true)
if [ -n "$current" ]; then
local normalized
normalized=$(echo "$current" \
| sed 's/^[[:space:]]*//;s/[[:space:]]*=[[:space:]]*/ = /;s/[[:space:]]\+/ /g')
if [ "$normalized" = "$expected" ]; then
log "postgresql.conf '${key}' already set to ${value}"
return 1
fi
sudo sed -i -E \
"s|^[[:space:]]*${key}[[:space:]]*=.*|${expected}|" \
"$file"
log "Updated postgresql.conf '${key}' = ${value}"
return 0
fi
if grep -qE "^[[:space:]]*#[[:space:]]*${key}[[:space:]]*=" "$file"; then
sudo sed -i -E \
"s|^[[:space:]]*#[[:space:]]*${key}[[:space:]]*=.*|${expected}|" \
"$file"
log "Uncommented postgresql.conf '${key}' = ${value}"
return 0
fi
echo "$expected" | sudo tee -a "$file" >/dev/null
log "Appended postgresql.conf '${key}' = ${value}"
return 0
}
normalize_cidr() {
local ip="$1"
if [[ "$ip" != */* ]]; then
echo "${ip}/32"
else
echo "$ip"
fi
}
# ========================================================================= pg_hba helpers
# Remove managed TCP host-all rules for localhost and remote addresses.
#
# We intentionally manage only:
#
# host all all 127.0.0.1/32 ...
# host all all ::1/128 ...
# host all all <remote-cidr> ...
#
# Other pg_hba rules are left untouched.
remove_managed_host_rules() {
sudo sed -i -E \
'/^[[:space:]]*host[[:space:]]+all[[:space:]]+all[[:space:]]+(127\.0\.0\.1\/32|::1\/128)([[:space:]]|$)/d' \
"$HBA_FILE"
}
remote_hba_snapshot() {
sudo grep -E \
'^[[:space:]]*host[[:space:]]+all[[:space:]]+all[[:space:]]+' \
"$HBA_FILE" 2>/dev/null \
| grep -Ev \
'[[:space:]](127\.0\.0\.1/32|::1/128)([[:space:]]|$)' \
|| true
}
remove_remote_hba_rules() {
sudo sed -i -E \
'/^[[:space:]]*host[[:space:]]+all[[:space:]]+all[[:space:]]+(127\.0\.0\.1\/32|::1\/128)([[:space:]]|$)/b
/^[[:space:]]*host[[:space:]]+all[[:space:]]+all[[:space:]]+/d' \
"$HBA_FILE"
}
ensure_local_hba_rules() {
local before after
before="$(
sudo grep -E \
'^[[:space:]]*host[[:space:]]+all[[:space:]]+all[[:space:]]+(127\.0\.0\.1\/32|::1\/128)([[:space:]]|$)' \
"$HBA_FILE" 2>/dev/null \
|| true
)"
# Remove existing managed localhost host rules first so that
# re-runs produce exactly one canonical rule for each address.
remove_managed_host_rules
{
echo "host all all 127.0.0.1/32 ${AUTH}"
echo "host all all ::1/128 ${AUTH}"
} | sudo tee -a "$HBA_FILE" >/dev/null
after="$(
sudo grep -E \
'^[[:space:]]*host[[:space:]]+all[[:space:]]+all[[:space:]]+(127\.0\.0\.1\/32|::1\/128)([[:space:]]|$)' \
"$HBA_FILE" 2>/dev/null \
|| true
)"
if [ "$before" != "$after" ]; then
return 0
fi
return 1
}
sync_remote_hba_allowlist() {
local -a desired=("$@")
local before after cidr line
before="$(remote_hba_snapshot)"
# Remove all remote host-all rules while preserving/recreating
# localhost rules separately.
remove_remote_hba_rules
for cidr in "${desired[@]}"; do
line="host all all ${cidr} ${AUTH}"
echo "$line" | sudo tee -a "$HBA_FILE" >/dev/null
log "pg_hba allow: ${cidr} (${AUTH})"
done
after="$(remote_hba_snapshot)"
if [ "$before" != "$after" ]; then
return 0
fi
return 1
}
configure_pg_hba() {
local local_changed remote_changed
local_changed=false
remote_changed=false
if ensure_local_hba_rules; then
local_changed=true
fi
if sync_remote_hba_allowlist "${DESIRED_CIDRS[@]}"; then
remote_changed=true
fi
if [ "$local_changed" = true ] || [ "$remote_changed" = true ]; then
NEED_RESTART=true
fi
}
# ========================================================================= Firewall
configure_firewall() {
local port="$1"
if ! command -v ufw &>/dev/null; then
log "ufw not installed — skipping firewall"
return 0
fi
if sudo ufw status 2>/dev/null | grep -qE "(${port}/tcp|${port}\\s)"; then
log "Firewall rule for ${port}/tcp already exists"
return 0
fi
sudo ufw allow "${port}/tcp" comment 'PostgreSQL (rhctl)'
log "Allowed ${port}/tcp in ufw"
}
# ========================================================================= PostgreSQL discovery
if ! command -v psql &>/dev/null; then
echo "[ERROR] psql not found. Run install.sh first."
exit 1
fi
if ! command -v pg_lsclusters &>/dev/null; then
echo "[ERROR] pg_lsclusters not found."
echo "[ERROR] This script requires the Debian/Ubuntu postgresql-common package."
exit 1
fi
CLUSTER_INFO="$(pg_lsclusters -h 2>/dev/null | awk '$2 == "main" { print; exit }')"
if [ -z "$CLUSTER_INFO" ]; then
echo "[ERROR] PostgreSQL 'main' cluster not found."
echo "[ERROR] Available clusters:"
pg_lsclusters || true
exit 1
fi
PG_VERSION="$(echo "$CLUSTER_INFO" | awk '{print $1}')"
PG_CLUSTER="$(echo "$CLUSTER_INFO" | awk '{print $2}')"
CLUSTER_PORT="$(echo "$CLUSTER_INFO" | awk '{print $3}')"
CLUSTER_STATUS="$(echo "$CLUSTER_INFO" | awk '{print $4}')"
CONF_DIR="/etc/postgresql/${PG_VERSION}/${PG_CLUSTER}"
CONF_FILE="${CONF_DIR}/postgresql.conf"
HBA_FILE="${CONF_DIR}/pg_hba.conf"
if [ ! -f "$CONF_FILE" ] || [ ! -f "$HBA_FILE" ]; then
echo "[ERROR] Expected PostgreSQL config files were not found:"
echo "[ERROR] ${CONF_FILE}"
echo "[ERROR] ${HBA_FILE}"
exit 1
fi
log "Detected PostgreSQL cluster: ${PG_VERSION}/${PG_CLUSTER}"
log "Current cluster port: ${CLUSTER_PORT}"
log "Current cluster status: ${CLUSTER_STATUS}"
# ========================================================================= listen / port
if set_conf_kv "listen_addresses" "'*'" "$CONF_FILE"; then
NEED_RESTART=true
fi
if set_conf_kv "port" "${RHCTL_PG_PORT}" "$CONF_FILE"; then
NEED_RESTART=true
fi
AUTH="$RHCTL_PG_AUTH_METHOD"
# ========================================================================= pg_hba
DESIRED_CIDRS=()
ALLOW_IPS_EXPLICIT=false
if [ "${#IPS[@]}" -gt 0 ]; then
ALLOW_IPS_EXPLICIT=true
for raw in "${IPS[@]}"; do
ip="$(echo "$raw" | xargs)"
[ -z "$ip" ] && continue
DESIRED_CIDRS+=("$(normalize_cidr "$ip")")
done
fi
if [ "$ALLOW_IPS_EXPLICIT" = true ] && [ "${#DESIRED_CIDRS[@]}" -eq 0 ]; then
echo "[ERROR] --allowed-ips produced an empty allow-list"
exit 1
fi
if [ "${#DESIRED_CIDRS[@]}" -eq 0 ]; then
log "No --allowed-ips — allowing local TCP access only"
else
log "Configuring remote pg_hba allow-list"
fi
configure_pg_hba
# ========================================================================= firewall
configure_firewall "$RHCTL_PG_PORT"
# ========================================================================= Start / restart PostgreSQL
if [ "$NEED_RESTART" = true ]; then
log "Restarting PostgreSQL to apply configuration"
if ! sudo systemctl restart postgresql; then
echo "[ERROR] Failed to restart PostgreSQL"
sudo systemctl status postgresql --no-pager || true
exit 1
fi
else
if ! systemctl is-active --quiet postgresql; then
warn "PostgreSQL service is not active — attempting start"
if ! sudo systemctl start postgresql; then
echo "[ERROR] Failed to start PostgreSQL"
sudo systemctl status postgresql --no-pager || true
exit 1
fi
else
log "PostgreSQL service is already active"
fi
fi
# ========================================================================= Wait until PostgreSQL accepts connections
if ! command -v pg_isready &>/dev/null; then
echo "[ERROR] pg_isready not found."
exit 1
fi
log "Waiting for PostgreSQL on 127.0.0.1:${RHCTL_PG_PORT}"
READY=false
for _ in $(seq 1 30); do
if pg_isready \
-h 127.0.0.1 \
-p "$RHCTL_PG_PORT" \
-d postgres \
>/dev/null 2>&1; then
READY=true
break
fi
sleep 1
done
if [ "$READY" != true ]; then
echo "[ERROR] PostgreSQL is not accepting connections on"
echo "[ERROR] 127.0.0.1:${RHCTL_PG_PORT}"
echo
echo "[ERROR] Cluster status:"
pg_lsclusters || true
echo
echo "[ERROR] Listening sockets:"
sudo ss -lntp | grep -E "(:${RHCTL_PG_PORT}[[:space:]]|postgres)" || true
echo
echo "[ERROR] PostgreSQL service status:"
sudo systemctl status postgresql --no-pager || true
exit 1
fi
log "PostgreSQL is accepting connections on 127.0.0.1:${RHCTL_PG_PORT}"
# ========================================================================= Verify runtime configuration
RUNTIME_PORT="$(
PGCONNECT_TIMEOUT=5 \
sudo -u postgres psql \
-p "$RHCTL_PG_PORT" \
-d postgres \
-tAc "SHOW port;" \
| tr -d '[:space:]'
)"
RUNTIME_LISTEN="$(
PGCONNECT_TIMEOUT=5 \
sudo -u postgres psql \
-p "$RHCTL_PG_PORT" \
-d postgres \
-tAc "SHOW listen_addresses;" \
| tr -d '[:space:]'
)"
if [ "$RUNTIME_PORT" != "$RHCTL_PG_PORT" ]; then
echo "[ERROR] PostgreSQL runtime port mismatch."
echo "[ERROR] Expected: ${RHCTL_PG_PORT}"
echo "[ERROR] Actual: ${RUNTIME_PORT}"
exit 1
fi
log "Runtime listen_addresses=${RUNTIME_LISTEN}"
log "Runtime port=${RUNTIME_PORT}"
# ========================================================================= Final output
echo "============================================="
echo "[INFO] PostgreSQL server configured"
echo "[INFO] LISTEN=* PORT=${RHCTL_PG_PORT} AUTH=${AUTH}"
if [ "${#DESIRED_CIDRS[@]}" -gt 0 ]; then
echo "[INFO] ALLOW_IPS=${DESIRED_CIDRS[*]}"
else
echo "[INFO] ALLOW_IPS=(none — local 127.0.0.1 / ::1 only)"
fi
echo "[INFO] Next: create a database with"
echo "[INFO] ./db.sh --action create --port ${RHCTL_PG_PORT}"
echo "============================================="