1

There is a Postgres database that I connect to with SQLAlchemy.

I currently have the database's connection parameters (database name, host, port, username, password) all hard coded in the Python file. I want to change that.

I read here that one should store these parameters in environment variables. Of the five connection parameters, what should I store in environment variables?

Obviously I will store password, but should I additionally store username and host? What is the convention here?

ChrisGPT was on strike
  • 127,765
  • 105
  • 273
  • 257
Intrastellar Explorer
  • 3,005
  • 9
  • 52
  • 119

3 Answers3

2

Why hardcode anything? Just move all of these parameters to environment variables.

Mureinik
  • 297,002
  • 52
  • 306
  • 350
2

Putting settings in environment variables isn't just about security. It's also about flexibility. Anything that's likely to change between environments is a good candidate to be put in environment variables.

Consider your database. Is it likely that the host, user name, and database name might be different on different environments? I suspect so. Many projects might use a database on localhost or on a Docker image called db in docker-compose.yml in development, and to use a dedicated database server or hosted database in production.

A common pattern is to encode your entire database connection string in a single environment variable DATABASE_URL. The format¹ is something like

<engine>://<user>:<password>@<host>:<port>/<database>

For example, you might use something like

postgres://db_user:password@localhost/app_db

Many database libraries, including SQLAlchemy can connect to databases using this single string directly.


¹This is a specialization on regular URL syntax.

ChrisGPT was on strike
  • 127,765
  • 105
  • 273
  • 257
1

One of the way to do this will be as below from security point of view. Assuming that we classify password as sensitive data and we want to encrypt only the password. Rest information can be either in environment variables or into the config files.

1) Have a random value based salt that is specific to the server generated at the time of encryption program invocation. This value is saved into file. Lets call it salt.bin

2) Change permission of the salt.bin file such that it is readable only operating system user which will run your program.

3) Have security personal/entrusted personal enter password to the encryption program and saved the encrypted value into a file. Lets call it db_config.bin.

4) Change permission of the db_config.bin file such that it is readable only by operating system user which will run your program.

Now during program execution time, let program read salt.bin file and db_config.bin file. Decrypt db_config.bin by using salt.bin. Program uses this password along with config files values for host, port, and other details to connect to database .

All of above can be accomplished with python.See here.

Jignesh
  • 88
  • 3