These documents only explain about how to access environment variables in dbt SQL model. How can I do it in dbt dython model?
While you cannot expand jinja templates in python dbt models, i used to have a workaround.
Suppose you have variable defined in project config.
dbt_project.yml:
...
vars:
my_var: my_value
then, you can use jinja in model config itself to pass this value.
my_model_scheme.yml
models:
- name: model_my
config:
materialized: incremental
tags: [ 'python' ]
my_var: '{{ var("my_var") }}'
And finally get it in model.
model_my.py
def model(dbt, session):
print(dbt.config.get("my_var"))
I want to extend the existing answer. With environment variables, you do not need to set the configuration in the dbt_project.yml, even it is considered as best practice.
An alternative approach would be to use
.env:
my_var=ABCD
Here you can then directly access the variable using env_var
my_model_scheme.yml
models:
- name: model_my
config:
materialized: incremental
tags: [ 'python' ]
my_var: '{{ env_var("my_var") }}'
And the rest is the same
model_my.py
def model(dbt, session):
print(dbt.config.get("my_var"))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With