What is Dynaconf and Why use it?
Dynaconf is a flexible, multi-environment configuration management tool for Python applications.
Traditionally, developers handled configurations using separate files for each environment (like settings.py
or .env
files).
While this works, it often requires manual changes at runtime or hardcoding values for different environments.
It supports environment variables, .env
files, and even hierarchical settings stored in JSON, YAML, or TOML.
Initialize Dynaconf
To initialize Dynaconf run,
$ dynaconf init -f toml
It will create the following
.
├── config.py # Where you import your settings object (required)
├── .secrets.toml # Sensitive data like passwords and tokens (optional)
└── settings.toml # Application settings (optional)
Dynaconf Configuration
Place the settings.toml
file at the root of the repo and define your settings.
[development]
DEBUG = true
DATABASE_URL = "sqlite:///development.db"
[testing]
DEBUG = true
DATABASE_URL = "sqlite:///testing.db"
[production]
DEBUG = false
DATABASE_URL = "postgresql://user:pass@localhost/db"
We have 3 environments — development
, testing
and production
.
Managing Secrets with Dynaconf
1. Using .secrets
Files
Dynaconf supports storing sensitive data in a .secrets
file (e.g., .secrets.toml
, .secrets.yaml
, etc.).
2. Vault Integration
For more secure storage, Dynaconf can load secrets from a Vault server (e.g., HashiCorp Vault).
To use Vault with Dynaconf:
-
Set up a Vault server (locally or via Docker).
-
Install Dynaconf with Vault support:
pip install dynaconf[vault]
-
Configure Vault in your
.env
or environment variables
VAULT_ENABLED_FOR_DYNACONF=true
VAULT_URL_FOR_DYNACONF="[http://localhost:8200](http://localhost:8200/)"
VAULT_TOKEN_FOR_DYNACONF="your-root-token"
3. Redis for Secrets Storage
To use Redis:
-
Set up Redis via Docker:
docker run -d -p 6379:6379 redis
-
Install Dynaconf with Redis support:
pip install dynaconf[redis]
-
Configure Redis in your
.env
or environment variables:
REDIS_ENABLED_FOR_DYNACONF=true
REDIS_HOST_FOR_DYNACONF=localhost
REDIS_PORT_FOR_DYNACONF=6379
Secrets can now be stored and accessed from Redis, ensuring they are centrally managed and securely distributed across all instances of your application.
4. Using .env
Files
For simple use cases, Dynaconf can load environment variables from a .env
file.
This file can hold your secrets in plain text, which is then loaded by Dynaconf when the application starts. To enable .env
file loading, use:
from dynaconf import Dynaconf
settings = Dynaconf(load_dotenv=True)
Example .env
file:
DYNACONF_API_KEY=12345abcdef
DYNACONF_DB_PASSWORD=supersecurepassword