0
0
DbtHow-ToBeginner ยท 3 min read

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 named VARIABLE_NAME.
  • env_var('VARIABLE_NAME', 'default_value'): Returns the environment variable value or default_value if 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_var in 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

UsageDescription
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 contextWorks in SQL models, macros, and configs where Jinja renders
Avoid in YAML keysenv_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.