-
Notifications
You must be signed in to change notification settings - Fork 0
/
postgres.py
115 lines (73 loc) · 2.72 KB
/
postgres.py
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
from fabric.api import cd, env, put, sudo, task
from fabric.contrib import files
import utils
@task
def install():
"""
Install the PostgreSQL server.
:Example:
fab --config=config/local.conf local postgres.install
"""
sudo('apt-get -y install libpq-dev postgresql postgresql-contrib')
@task
def restart():
"""
Restart the PostgreSQL server.
:Example:
fab --config=config/local.conf local postgres.restart
"""
sudo('service postgresql restart')
@task
def config():
"""
Customize the configuration files of the PostgreSQL server.
:Example:
fab --config=config/local.conf local postgres.config
"""
base_directory = '/etc/postgresql/{}/main'.format(env.postgres_version)
conf_directory = '{}/conf.d'.format(base_directory)
if not files.exists(conf_directory):
# Create the "conf.d" directory.
sudo('mkdir -p {}'.format(conf_directory))
# Set directory permission to "744".
sudo('chmod 744 {}'.format(conf_directory))
# Set directory owner to "postgres".
usr = grp = 'postgres'
sudo('chown {}:{} {}'.format(usr, grp, conf_directory))
if env.environment == 'live':
config_live(base_directory, conf_directory)
else:
config_local(base_directory, conf_directory)
def config_live(base_directory, conf_directory):
"""
Upload custom configuration files for live server.
"""
def config_local(base_directory, conf_directory):
"""
Upload custom configuration files for local server.
"""
local_path = utils.file_path('postgres/local.conf')
remote_path = '{}/local.conf'.format(conf_directory)
result = put(local_path, remote_path, mode=0644, use_sudo=True)
if result.succeeded:
pg_conf = '{}/postgresql.conf'.format(base_directory)
files.append(pg_conf, "include_dir = 'conf.d'", use_sudo=True)
# Set file owner to "postgres".
usr = grp = 'postgres'
sudo('chown {}:{} {}'.format(usr, grp, remote_path))
# Grant access to remote clients.
hba_conf = '{}/pg_hba.conf'.format(base_directory)
files.append(hba_conf, 'host all all 0.0.0.0/0 md5', use_sudo=True)
@task
def user_create(username, password):
"""
Create the new database role/user.
:Example:
fab --config=config/local.conf local postgres.user_create:username=hello,password=world
"""
# Hash the password that will be passed to PostgreSQL.
password = utils.pghash(username, password)
command = """
psql -c "CREATE ROLE {username} WITH {options} ENCRYPTED PASSWORD '{password}'";
""".format(username=username, password=password, options=env.postgres_options)
sudo(command, user='postgres')