Overview
KrakenD’s Flexible Configuration system allows you to use templates instead of a monolithic JSON file. This enables:- Variables - Environment-specific settings
- Partials - Reusable configuration snippets
- Logic - Loops and conditionals
- Maintainability - Organized, DRY configurations
Example Template
The playground includeskrakend-flexible-config.tmpl as a demonstration.
Template File
Fromconfig/krakend/krakend-flexible-config.tmpl:
Environment Variables
Fromconfig/krakend/settings/dev/env.json:
Compiling the Configuration
Using Make
From theMakefile:
Run the Command
krakend-flexible-config.compiled.json with all variables resolved and templates included.
Template Syntax
KrakenD uses Go template syntax.1. Variables
Access environment variables with.env:
2. Including Partials
Reuse configuration snippets:include function inserts the content of partials/extra_config.tmpl.
3. Templates
Use named templates:template function renders templates/sample_template.tmpl with the current context (.).
4. Loops
Iterate over arrays:env.json contains:
5. Conditionals
Directory Structure
Organize templates and settings:Environment Variables
Configure the flexible configuration system:| Variable | Description | Example |
|---|---|---|
FC_ENABLE | Enable flexible configuration | 1 |
FC_SETTINGS | Path to settings directory | /etc/krakend/settings/dev |
FC_PARTIALS | Path to partials directory | /etc/krakend/partials |
FC_TEMPLATES | Path to templates directory | /etc/krakend/templates |
FC_OUT | Output file for compiled config | /etc/krakend/compiled.json |
Use Cases
1. Environment-Specific Configuration
Template:settings/dev/env.json):
settings/prod/env.json):
2. DRY Backend Configurations
Partial:partials/auth_backend.tmpl
3. Dynamic Endpoint Generation
Benefits
Maintainability
Before (monolithic):- 5,000+ line JSON file
- Duplicated configuration
- Hard to find specific settings
- Difficult to change
- Main template: 200 lines
- Partials: 10-50 lines each
- Organized by feature
- Change once, apply everywhere
Environment Management
Team Collaboration
Testing
Validate template compilation:Advanced Features
Custom Functions
KrakenD provides template functions:Environment Variables from OS
Access OS environment variables:Best Practices
1. Keep Templates Simple
✓ Good:2. Use Descriptive Variable Names
✓ Good:3. Document Template Variables
Add comments to env.json:4. Version Control Settings
Comparison: Regular vs Flexible
| Aspect | Regular JSON | Flexible Config |
|---|---|---|
| File | Single JSON | Multiple templates |
| Variables | Hard-coded | Environment-specific |
| Reusability | Copy-paste | Partials/templates |
| Environments | Separate files | Same template, different settings |
| Complexity | Simple for small configs | Better for large configs |
| Learning Curve | JSON only | Go templates |