Skip to content
lorebow

Config

Anything that changes between deploys comes from environment variables, so one release runs anywhere.

KFounder and editor 167 words 1 min read Find it on the map
On this page

Store config in the environment. Config is everything that changes between deploys: database addresses, credentials for other services, the hostname the app runs on. Code is what stays the same.

A quick test: could you make the repository public right now without leaking a password? If not, config is mixed into your code.

#Move it out of the code

db.pypython
import mysql.connector
 
db = mysql.connector.connect(
    host="prod-db.internal",
    user="shop",
    password="s3cret!",  # now in git history forever
    database="shop",
)

os.environ["DB_HOST"] fails at startup if the variable is missing, which is what you want: a clear error now beats connecting to the wrong database later.

#One release, many environments

The same code, different configStep 1 of 3
Releasesame buildDev envDB_HOST=localhostProd envDB_HOST=prod-dbLaptoplocal MySQLProductionmanaged MySQL

1.One build

The code is built once. It contains no hostnames and no passwords.

#Use a .env file locally

Typing variables into every terminal gets old. Keep them in a .env file, load it at startup, and never commit it.

.envtext
DB_HOST=localhost
DB_USER=shop
DB_PASSWORD=devpassword
DB_NAME=shop
main.pypython
from dotenv import load_dotenv
 
load_dotenv()  # reads .env if it exists; real environment variables win
.gitignoretext
.env

Commit a .env.example with the variable names and fake values instead, so the next developer knows what to set.

Referenced by