Skip to content

Commit 2a2a5f2

Browse files
committed
Merge pull request alphagov#134 from alphagov/add-postgres-sync-command
Add a postgres sync command
2 parents c59bedf + fff1ea8 commit 2a2a5f2

File tree

3 files changed

+29
-0
lines changed

3 files changed

+29
-0
lines changed

README.md

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -73,3 +73,15 @@ and ensure that you do not have the following option anywhere in your
7373
`~/.ssh/config`:
7474

7575
ForwardAgent yes
76+
77+
## Syncing postgres machines
78+
79+
An example
80+
81+
`fab <env> -H '<src_db>' postgresql.sync:<db_name>,<dst_db> -A`
82+
83+
the -A must be specified to forward the agent
84+
85+
This will sync the specified database `<db_name>` from the machine with the
86+
hostname of `<src_db>` to the machine with hostaname `<dst_db>`. It will destroy
87+
data on the destination db

fabfile.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,7 @@
3030
import nagios
3131
import nginx
3232
import ntp
33+
import postgresql
3334
import puppet
3435
import rabbitmq
3536
import rkhunter

postgresql.py

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
from fabric.api import task, sudo, env, settings, run
2+
from fabric.utils import abort
3+
4+
@task
5+
def sync(database, dest_machine):
6+
# the agent forwarding is required for the ssh command to the destination
7+
# postgres server to work - this saves copying a temporary file down and
8+
# back up again. We cant use fabrics sudo context manager because the
9+
# command after the pipe should not run as the postgres user.
10+
# The combination of "--schema public" and "--clean" in the pg_restore
11+
# command clears all existing tables in the public schema before restoring
12+
# the tables and data
13+
with settings(forward_agent=True):
14+
run('sudo -iupostgres pg_dump -Fc {0} | ssh {1} '
15+
'"sudo -upostgres pg_restore --clean --single-transaction '
16+
'--schema public --dbname {0}"'.format(database, dest_machine))

0 commit comments

Comments
 (0)