Understanding dbt Variables
Variables in dbt serve two primary purposes:- Make code reusable - Define values once and reference them throughout your project
- Enable flexibility - Change behavior without modifying code
- Project variables - Defined in
dbt_project.yml - Command-line variables - Passed at runtime
- Environment variables - Accessed via Jinja macros
Defining Variables in dbt_project.yml
The simplest way to define variables is in yourdbt_project.yml file:
var() function.
Using Variables in Models
Once defined, you can reference variables in your models using thevar() function:
var() function has two parameters:
- The variable name
- An optional default value that’s used if the variable isn’t defined
Variable BehaviorWhen you use the
var() function:- It will use the variable from
dbt_project.ymlif defined - Command-line variables override values from
dbt_project.yml - If no variable is found and no default is specified, dbt will raise an error
- Environment-specific variables (
dev,prod) are only used when running in that environment
Passing Variables at Runtime
For maximum flexibility, pass variables at runtime using the--vars flag:
dbt_project.yml.
Working with Environment Variables
You can access environment variables using theenv_var Jinja function:
Security NoteNever use
env_var() for credentials that should remain secret. These values could be exposed in compiled SQL or logs. Instead, use your platform’s secure environment variable handling for credentials.Advanced Variable Techniques
Conditional Logic with Variables Variables allow you to implement conditional logic in your models:Best Practices for Variables
Example: Well-Structured Variables