S
S
Stanislav Gordienko2015-11-22 01:31:22
PostgreSQL
Stanislav Gordienko, 2015-11-22 01:31:22

How to create database and user in Postgresql from script?

Hello everyone,
Until recently my script worked great to prepare a new server to run a Django application with this wonderful database.
Here is the actual part for setting up the database and creating the user and database:

sudo apt-get install -y postgresql postgresql-contrib libpq-dev
sed -i "s|^#\(listen_addresses\) = '.*'|\1 = 'localhost'|" /etc/postgresql/9.4/main/postgresql.conf
service postgresql restart

su postgres -c "
psql template1 <<END
CREATE USER django_db_user;
ALTER ROLE django_db_user WITH ENCRYPTED PASSWORD 'Password';
\q
END
createdb -O django_db_user django_db
exit
psql template1 <<END
GRANT ALL PRIVILEGES ON DATABASE django_db TO django_db_user;
\q
END
"

And so I connect with the following settings to the database from Django:
DATABASES = {
    'default': {
        'ENGINE':       'django.db.backends.postgresql_psycopg2',
        'NAME':         'django_db',
        'USER':         'django_db_user',
        'PASSWORD':     'Password',
        'HOST':         'localhost',
        'PORT':         '',
        'CONN_MAX_AGE': None,
    }
}

But just yesterday I saw that a connection could not be established from the Django application. Says the password is wrong. I compared the database configurations on the live server and the local one, they are identical. Unless the Ubuntu version is different (15.4 and 15.10).
How do you configure Postgresql from a script?
Thank you.
Added Dec 14 :
Do you think it would be safe if I make a trust connection for local in production in pg_hba.conf?
local my_database all trust

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question