2 # {{ ansible_managed }}
6 CLUSTER_VERSION
="{{ postgres_version }}"
7 CLUSTER_NAME
="{{ postgres_cluster_name }}"
8 PRIMARY_CLUSTER_HOST
="{{ postgres_primary.host }}"
9 PRIMARY_CLUSTER_PORT
="{{ postgres_primary.port }}"
10 PRIMARY_CLUSTER_USER
="{{ postgres_primary.replication_user }}"
11 PRIMARY_CLUSTER_PASSWORD
="{{ postgres_primary.replication_password }}"
12 {% if postgres_primary.replication_dbname is defined
%}
13 PRIMARY_CLUSTER_DBNAME
=" dbname='{{ postgres_primary.replication_dbname }}'"
16 read -p "You are about to clone the primary cluster (${PRIMARY_CLUSTER_HOST}:${PRIMARY_CLUSTER_PORT}) with pg_basebackup. This will replace the local ${CLUSTER_VERSION}/${CLUSTER_NAME} cluster. Are you sure? [y/n] " -r go
18 if [ "$go" != "y" ]; then
23 BACKUP_DATE
=$(date +%s)
25 echo "Stopping PostgreSQL"
26 pg_ctlcluster
"${CLUSTER_VERSION}" "${CLUSTER_NAME}" stop
|| true
28 echo "Cleaning up old cluster directory"
29 sudo
-u postgres
mv "/var/lib/postgresql/${CLUSTER_VERSION}/${CLUSTER_NAME}"{,"_${BACKUP_DATE}"}
31 echo "Creating new directory"
32 sudo
-u postgres
mkdir -p "/var/lib/postgresql/${CLUSTER_VERSION}/${CLUSTER_NAME}"
34 echo "Get backup from primary server"
36 time "/usr/lib/postgresql/${CLUSTER_VERSION}/bin/pg_basebackup" --format=p
-R \
37 -d "host='${PRIMARY_CLUSTER_HOST}' port='${PRIMARY_CLUSTER_PORT}' user='${PRIMARY_CLUSTER_USER}' password='${PRIMARY_CLUSTER_PASSWORD}' ${PRIMARY_CLUSTER_DBNAME} sslmode=require" \
38 -D "/var/lib/postgresql/${CLUSTER_VERSION}/${CLUSTER_NAME}/"
40 echo "Restoring .conf and server certificate"
41 sudo
-u postgres
cp -a "/var/lib/postgresql/${CLUSTER_VERSION}/${CLUSTER_NAME}_${BACKUP_DATE}/"{*.conf
,server.crt
,server.key
} "/var/lib/postgresql/${CLUSTER_VERSION}/${CLUSTER_NAME}/"
43 echo "Ensure rights are correcly set"
44 chown
-R postgres
:postgres
"/var/lib/postgresql/${CLUSTER_VERSION}/"
45 chmod 0700 "/var/lib/postgresql/${CLUSTER_VERSION}/"
46 chmod -R o
-rwx "/var/lib/postgresql/${CLUSTER_VERSION}/"
48 echo "Starting PostgreSQL"
49 sudo pg_ctlcluster
"${CLUSTER_VERSION}" "${CLUSTER_NAME}" start