Define and Update {{ var }} to be used across different models

The problem I’m having

So I pass a variable to a model using this command

dbt run –select model1 –vars ‘{my_var: None}’

In my model1, I want to update this global level variable my_var using the output of a pre_hook.

But I’m struggling to come up with the right syntax. I want to use this updated my_var across my models in job runs if i run models using select tag: syntax

The context of why I’m trying to do this

I’m generating a unique ID, which is to be used in all my downstream models. So I want to generate this Unique Id once by calling the macro in model1.

and set the global variable with this unique id.

then all my remaining models (model2, model3, 4 etc) will get the updated value using {{ var }}.

What I’ve already tried

inside my pre_hook block of statements, i tried adding this after my macro

"set var('my_var') = {{ this._pre_hook[0] }}",

Some example code or error messages

pre_hook = [
    "my_macro_which_generates_unique_id()",
    "set var('my_var') = {{ this._pre_hook[0] }}",
    "{{ log('[LOG]: ID value after pre-hook: ' ~ var('my_var'), info=True) }}",
]

The output doesnt show the updated id.
03:14:44 [LOG]: ID value after pre-hook: None

You cannot make a model set a “dbt var” and have other models read that var.

Note: @Jeremy Yeo originally posted this reply in Slack. It might not have transferred perfectly.

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.