Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use variables in dbt macros

Tags:

dbt

I am trying to use a variable passed in dbt run command in a macro. How can I use it

    {% set override_schema_name = vars('override_schema_name') %}


    {%- set default_schema = target.schema -%}
    {%- if custom_schema_name is none -%}

        {{ default_schema }}

    {%- else -%}

        {{ default_schema }}_{{  override_schema_name| trim }}

    {%- endif -%}

{%- endmacro %} 

In this example i am running dbt run --vars '{"override_schema_name":"someschema"}', but this is throwing error that variable is not defined.

like image 991
code_code Avatar asked Nov 01 '25 10:11

code_code


1 Answers

There are a few things wrong in your code:

  1. The macro name to access the value of a variable is var, not vars. So your first line should be {% set override_schema_name = var('override_schema_name') %}

  2. You should declare any vars in your project.yml file before using them in a macro or elsewhere in your project:

name: my_dbt_project
version: 1.0.0

config-version: 2

# Define variables here
vars:
  override_schema_name: something

Alternatively, you can provide a default value to your var call in the macro:

{% set override_schema_name = var('override_schema_name', target.schema) %}

After making those changes, your dbt run command should work.

var docs: https://docs.getdbt.com/reference/dbt-jinja-functions/var "Using Variables" guide: https://docs.getdbt.com/docs/building-a-dbt-project/building-models/using-variables

like image 166
tconbeer Avatar answered Nov 04 '25 01:11

tconbeer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!