Search code examples
dbt

reference a global var in yml file in dbt


Referencing a global variable in a .yml file in dbt

For example, if I have a column or a table name that is defined as a global in my dbt_project.yml file:

# dbt_project.yml

name: 'my_project'
version: '1.0.0'
config-version: 2

vars:
  my_var: 'my_special_var'

how can I reference my_var in a .yml file?


Solution

  • There are a couple of ways, if you use dbt core, you can export the environment variables e.g.

    export DBT_USER_NAME=andy
    

    then you can reference it in the yaml file:

    models:
      test_project:
        AA:
          databaseusername: {{ var("DBT_USER_NAME") }}
    

    you can also define variables in the yaml file

    vars:
      test_project:
        env: "dev"
        etl_schema: "etl"
    
    ...
    
    models:
      test_project:
        AA:
          database: test_{{ var("env") }}_raw
          schema: {{ var("etl_schema") }}
    

    then overwrite the variable value in the command line

    dbt run --vars '{"env": "prod"}'