Skip to main content

Running Macros with dbt run-operation

Learning objectives​

You will learn how to create an operational macro, pass arguments from the command line, and understand why dbt run-operation is different from dbt run.

1. Two ways to use a macro​

A macro is usually used in one of two ways:

PatternWhat happensCommand
SQL-generating macroThe macro returns SQL that becomes part of a modeldbt run
Operational macroThe macro performs an explicit taskdbt run-operation

Use operational macros for administrative or repeatable tasks such as logging, granting permissions, refreshing metadata, or running controlled DDL. Do not use them as a replacement for ordinary transformation models.

2. Create a standalone macro​

Create macros/hello_macro.sql:

{% macro hello_macro(name) %}
{{ log('Hello ' ~ name ~ '! dbt run-operation is working.', info=True) }}
{% endmacro %}

log() writes a message to the dbt output. This macro does not return a SELECT statement and does not create a relation.

3. Execute it​

From the root of the dbt project, run:

dbt run-operation hello_macro --args '{"name": "Ajay"}'

The exact timestamps and model count vary by dbt version. Look for this message:

Hello Ajay! dbt run-operation is working.

This proves that dbt discovered the macro, parsed the argument, and executed the macro.

4. Understand --args​

The value passed to --args is a mapping whose keys must match the macro parameters:

dbt run-operation hello_macro --args '{"name": "Priya"}'

A macro with two parameters might look like this:

{% macro report_table(database_name, schema_name, table_name) %}
{{ log(database_name ~ '.' ~ schema_name ~ '.' ~ table_name, info=True) }}
{% endmacro %}

Run it with:

dbt run-operation report_table --args '{"database_name": "BEEMS_TECHNE_ECOMM", "schema_name": "RAW", "table_name": "CUSTOMERS"}'

Keep arguments explicit and validate them before using them in DDL. Never accept arbitrary user input and concatenate it into a destructive statement without controls.

5. run-operation versus run​

# Calls one macro directly; it does not build models.
dbt run-operation hello_macro --args '{"name": "Ajay"}'

# Selects and builds a model.
dbt run --select stg_customers

dbt compile renders selected models without executing them, while dbt test executes data tests. Choosing the correct command is part of safe dbt development.

Practice​

  1. Change the macro so it logs Welcome <name>! You are learning dbt macros.
  2. Run it with your own name.
  3. Run dbt run-operation hello_macro without --args and observe the error.
  4. Add a default value with name='learner', then run it again without arguments.

Summary​

  • dbt run-operation executes a named macro directly.
  • --args passes a dictionary to macro parameters.
  • An operational macro does not build a model unless it explicitly runs database SQL.
  • Use dbt run for models and dbt compile to inspect generated SQL.