Skip to main content

02. Running Operations

️ What are dbt Operations?​

Operations in dbt are SQL or Jinja commands that can be executed outside of the normal model run flow.
They are typically used for:

  • Managing database objects (tables, views, grants)
  • Performing administrative tasks
  • Running custom macros or scripts

Operations are often combined with hooks to automate pre/post actions.


How to Run Operations​

  1. Using dbt CLI
dbt run-operation <macro_name> --args '{key: value}'
  • <macro_name> → Name of the macro you want to execute
  • --args → Optional arguments passed to the macro

️ Example: Running a Macro to Grant Access​

Macro definition (macros/grant_access.sql):

{% macro grant_access(table_name, role_name) %}
grant select on {{ table_name }} to role {{ role_name }};
{% endmacro %}

Run the macro via CLI:

dbt run-operation grant_access --args '{"table_name": "app.customers", "role_name": "analytics_team"}'

Explanation:

  • Executes a grant statement outside of the normal model run
  • Allows ad-hoc operations without altering models

️ Example: Logging an Operation​

Macro (macros/log_operation.sql):

{% macro log_operation(operation_name) %}
insert into audit_log (operation_name, executed_at)
values ('{{ operation_name }}', current_timestamp);
{% endmacro %}

Run via CLI:

dbt run-operation log_operation --args '{"operation_name": "refresh_customers"}'
  • Logs any custom operation for auditing
  • Useful for tracking manual runs or special maintenance tasks

Best Practices for Operations​

Keep operations idempotent – running multiple times should not break anything
Use macros for reusability
Combine with hooks for automation
Monitor dbt logs for auditing operations