How to Use env_var in dbt: Syntax, Example, and Tips
In dbt, use the
env_var function to access environment variables inside your project files. This lets you dynamically configure values like credentials or flags by calling {{ env_var('VARIABLE_NAME') }} in your SQL or YAML files.Syntax
The env_var function in dbt takes the name of an environment variable as a string and returns its value. You can also provide a default value if the environment variable is not set.
env_var('VARIABLE_NAME'): Returns the value of the environment variable namedVARIABLE_NAME.env_var('VARIABLE_NAME', 'default_value'): Returns the environment variable value ordefault_valueif the variable is not set.
jinja
{{ env_var('MY_ENV_VAR', 'default_value') }}Example
This example shows how to use env_var in a dbt model to conditionally filter data based on an environment variable.
sql
select * from {{ ref('my_source_table') }} where status = '{{ env_var("FILTER_STATUS", "active") }}'
Output
This query selects rows from the source table where the status matches the value of the FILTER_STATUS environment variable, or 'active' if FILTER_STATUS is not set.
Common Pitfalls
Common mistakes when using env_var include:
- Not setting the environment variable before running dbt, causing errors or unexpected defaults.
- Forgetting to provide a default value, which can cause dbt to fail if the variable is missing.
- Using
env_varin places where Jinja is not rendered, like some YAML keys, which will not work.
jinja
Wrong usage without default (can cause error if variable missing): {{ env_var('MISSING_VAR') }} Right usage with default: {{ env_var('MISSING_VAR', 'default_value') }}
Quick Reference
| Usage | Description |
|---|---|
| env_var('VAR_NAME') | Get environment variable value, error if missing |
| env_var('VAR_NAME', 'default') | Get environment variable or use default if missing |
| Use in Jinja context | Works in SQL models, macros, and configs where Jinja renders |
| Avoid in YAML keys | env_var does not work in YAML keys or some config fields |
Key Takeaways
Use env_var('VAR_NAME') to access environment variables in dbt with Jinja syntax.
Always provide a default value to avoid errors if the environment variable is not set.
env_var works only where Jinja templating is applied, like SQL models and macros.
Set environment variables in your shell or CI environment before running dbt.
Avoid using env_var in YAML keys or places where Jinja is not rendered.