Wicked Smart Data
LearnInsightsAboutContact
Sign InLet's Build
LearnInsightsAboutContact
Sign InLet's Build
Wicked Smart Data

Intelligence, automation, and expert execution — plus an elite library of free knowledge. We turn complexity into competitive advantage.

Start a conversation

Platform

  • Learning Paths
  • Insights
  • RSS Feed

Company

  • About
  • Contact
  • Work With Us

Legal

  • Privacy Policy
  • Terms of Service

© 2026 Wicked Smart Data. All rights reserved.

Intelligence · Automation · Advantage

All Insights
Data Engineering

Automating Snowflake RBAC Provisioning with dbt Hooks and Post-Deploy Scripts

When permissions live outside your transformation workflow, they're invisible to CI/CD, unversioned, and impossible to audit. Learn how to use dbt post-hooks, on-run-end macros, and post-deploy scripts to automatically grant, revoke, and audit Snowflake object-level permissions as part of every dbt run.

⚡ Practitioner22 min readNov 27, 2026Updated Nov 27, 2026
Automating Snowflake RBAC Provisioning with dbt Hooks and Post-Deploy Scripts
On this page
  • Introduction
  • Prerequisites
  • Understanding the Permission Gap in a Typical dbt Workflow
  • Model-Level Post-Hooks: Granting Access Right After Creation
  • Centralizing Grant Logic with Macros
  • Handling Schema-Level Grants for New Models
  • On-Run-End Hooks: Revoking Unexpected Access After Each Run
  • Building a Permission Audit Log in Snowflake
  • Post-Deploy Scripts: Grants That Run After dbt Completes
  • Handling the dbt `grants` Config Block (dbt Core 1.2+)
  • Hands-On Exercise
  • Common Mistakes & Troubleshooting
  • Summary & Next Steps

Automating Snowflake RBAC Provisioning with dbt Hooks and Post-Deploy Scripts: Granting, Revoking, and Auditing Object-Level Permissions as Part of Your Transformation Workflow

Introduction

Here's a situation you've probably lived through: a new mart model ships to production on a Friday afternoon. The stakeholder who requested it emails you on Monday morning asking why they can't see it in Tableau. You check Snowflake, and sure enough — the model materialized perfectly, but nobody granted SELECT on it to the ANALYST role. The permissions were forgotten in the sprint, as they always are.

Now multiply that by a team of five analytics engineers, a data platform with 200 models, and a business that onboards new analysts every other week. Access control becomes a full-time job layered on top of your actual job. The traditional fix — a separate runbook, a Slack channel for access requests, a weekly permissions sweep — doesn't scale, and more importantly, it decouples permissions from the code that creates the objects they protect. That's the root problem: when RBAC provisioning lives outside your transformation workflow, it's invisible to your CI/CD pipeline, unversioned, and impossible to audit consistently.

This lesson fixes that. By the end, you'll know how to use dbt's pre- and post-hooks, on-run-end hooks, and post-deploy callback scripts to grant and revoke Snowflake object permissions automatically as part of every dbt run. You'll also build a lightweight audit trail directly inside Snowflake so you can answer "who can see what, and when was that access granted?" without leaving your data platform.

What you'll learn:

  • How Snowflake RBAC maps to the objects dbt creates (tables, views, schemas, databases)
  • How to write post-hooks that grant role permissions at the model level using dbt's metadata
  • How to centralize permission logic using macros and the grant_access_to pattern
  • How to implement on-run-end hooks that sweep and revoke unexpected grants after each run
  • How to build a Snowflake-native permission audit log that captures every grant and revocation your dbt workflow makes

Prerequisites

You should be comfortable with:

  • Writing and running dbt models in a Snowflake-backed project — if you're newer to this, start with dbt Fundamentals: Transform Data with SQL in Your Warehouse first
  • Snowflake's RBAC model at a conceptual level, including roles, role hierarchies, and GRANT syntax — the Configuring Role-Based Access Control in Snowflake and BigQuery lesson covers this thoroughly
  • Basic Jinja templating in dbt (macros, run_query, model context variables)
  • A Snowflake account where your dbt service role has MANAGE GRANTS or SECURITYADMIN privilege

Understanding the Permission Gap in a Typical dbt Workflow

Before writing any code, let's make the problem concrete. When dbt runs CREATE OR REPLACE TABLE analytics.marts.customer_lifetime_value AS (...), Snowflake creates that table owned by the role that executed the statement — typically your dbt service account role, something like DBT_PROD_ROLE. No other role automatically gets access.

In a well-structured Snowflake environment, you have role hierarchy roughly like this:

SYSADMIN
  └── DBT_PROD_ROLE          (owns objects, runs transformations)
  └── ANALYST_ROLE           (reads from marts layer)
  └── DATA_SCIENCE_ROLE      (reads from staging + marts, needs raw access too)
  └── FINANCE_ANALYST_ROLE   (reads specific marts, nothing else)
  └── LOOKER_SERVICE_ROLE    (reads from marts for BI layer)

Every time dbt creates or replaces a model, the GRANT SELECT ON TABLE to ANALYST_ROLE needs to happen explicitly. If dbt replaces a table (which it does by default on full-refresh), the grants on that object are dropped along with the old table and must be re-applied. This is the trap that catches people: grants on replaced tables don't survive the replacement.

Warning

When dbt runs with --full-refresh or when a model uses the table materialization, Snowflake drops and recreates the underlying object. Any grants applied manually to the old object are silently lost. This is why manually applying grants after model creation is fundamentally broken — it only works until the next full-refresh.

This is distinct from views, where CREATE OR REPLACE VIEW preserves grants in some configurations, but you still can't rely on that behavior consistently. The only reliable solution is to apply grants programmatically as part of the model creation lifecycle.


Model-Level Post-Hooks: Granting Access Right After Creation

The most targeted approach is using dbt's post_hook configuration on individual models or groups of models. A post-hook is a SQL statement (or list of SQL statements) that dbt executes immediately after materializing a model, using the same connection and role.

Here's the simplest version, configured directly in a model's config block:

-- models/marts/finance/customer_lifetime_value.sql

{{
  config(
    materialized='table',
    post_hook=[
      "GRANT SELECT ON {{ this }} TO ROLE ANALYST_ROLE",
      "GRANT SELECT ON {{ this }} TO ROLE LOOKER_SERVICE_ROLE",
      "GRANT SELECT ON {{ this }} TO ROLE FINANCE_ANALYST_ROLE"
    ]
  )
}}

SELECT
  c.customer_id,
  c.customer_name,
  c.acquisition_channel,
  SUM(o.order_total) AS lifetime_value,
  COUNT(o.order_id) AS total_orders,
  MIN(o.created_at) AS first_order_date,
  MAX(o.created_at) AS most_recent_order_date
FROM {{ ref('stg_customers') }} c
LEFT JOIN {{ ref('stg_orders') }} o
  ON c.customer_id = o.customer_id
GROUP BY 1, 2, 3

The {{ this }} Jinja variable resolves to the fully-qualified object name — ANALYTICS.MARTS_FINANCE.CUSTOMER_LIFETIME_VALUE in this case — so your grant statement always targets the exact object dbt just built.

This works, but it has a critical problem: you're scattering grant logic across dozens of model files. When your security team asks "which roles have access to our finance mart layer?" you're hunting through SQL files rather than consulting a single policy definition. Let's fix that.


Centralizing Grant Logic with Macros

A much better architecture extracts permission logic into a reusable macro. The macro accepts a list of roles, constructs the appropriate GRANT statements, and executes them. This lets you define permissions in one place and reference them from model configs, schema-level configs in dbt_project.yml, or on-run-end hooks.

Create a file at macros/grants/grant_select_to_roles.sql:

{% macro grant_select_to_roles(roles, relation=this) %}
  {% if execute %}
    {% for role in roles %}
      {% set grant_sql %}
        GRANT SELECT ON {{ relation }} TO ROLE {{ role }}
      {% endset %}
      {% do run_query(grant_sql) %}
      {% do log("Granted SELECT on " ~ relation ~ " to role " ~ role, info=True) %}
    {% endfor %}
  {% endif %}
{% endmacro %}

A few things to note here:

  • The {% if execute %} guard is critical. dbt compiles macros twice — once during parsing and once during execution. Without this guard, your grants fire during the compilation phase before models even exist.
  • run_query() executes the SQL but doesn't return results to the model — it's a side-effect call.
  • Logging every grant action lets you see permission activity in dbt's stdout, which is useful for debugging and can be captured by your orchestrator's logging system.

Now models can reference this macro cleanly:

-- models/marts/finance/revenue_summary.sql

{{
  config(
    materialized='table',
    post_hook="{{ grant_select_to_roles(['ANALYST_ROLE', 'FINANCE_ANALYST_ROLE', 'LOOKER_SERVICE_ROLE']) }}"
  )
}}

SELECT
  DATE_TRUNC('month', order_date) AS revenue_month,
  product_category,
  SUM(revenue) AS total_revenue,
  COUNT(DISTINCT customer_id) AS unique_customers
FROM {{ ref('int_orders_enriched') }}
GROUP BY 1, 2

But we can go further. Rather than specifying roles in every model file, define them at the directory (schema) level in dbt_project.yml. This is where the real leverage is — you define a permission tier once and every model in that folder inherits it:

# dbt_project.yml

models:
  your_project_name:
    staging:
      +post_hook: "{{ grant_select_to_roles(['DATA_SCIENCE_ROLE']) }}"
    intermediate:
      +post_hook: "{{ grant_select_to_roles(['DATA_SCIENCE_ROLE', 'DBT_CI_ROLE']) }}"
    marts:
      finance:
        +post_hook: "{{ grant_select_to_roles(['ANALYST_ROLE', 'FINANCE_ANALYST_ROLE', 'LOOKER_SERVICE_ROLE']) }}"
      product:
        +post_hook: "{{ grant_select_to_roles(['ANALYST_ROLE', 'LOOKER_SERVICE_ROLE', 'DATA_SCIENCE_ROLE']) }}"
      executive:
        +post_hook: "{{ grant_select_to_roles(['EXEC_ANALYST_ROLE', 'LOOKER_SERVICE_ROLE']) }}"

Key insight

Defining grants at the directory level in dbt_project.yml means your permission model is co-located with your data model structure. When a new model is added to marts/finance/, it automatically inherits the finance tier's access policy. No separate ticket, no forgotten grant.

This is also where your multi-layer dbt project structure pays dividends — because your folder structure already encodes semantic meaning (staging vs. intermediate vs. marts), it naturally maps to permission tiers.


Handling Schema-Level Grants for New Models

There's a subtlety you'll hit when a dbt run adds a new model to a schema that your roles already have access to: the schema grant doesn't automatically cover new objects. In Snowflake, GRANT SELECT ON ALL TABLES IN SCHEMA is a point-in-time operation. GRANT SELECT ON FUTURE TABLES IN SCHEMA is what you want for forward-looking coverage.

Let's write a schema-level grant macro that handles both past and future objects:

{% macro grant_schema_access(database, schema, roles) %}
  {% if execute %}
    {% for role in roles %}
      {% set grant_existing %}
        GRANT USAGE ON SCHEMA {{ database }}.{{ schema }} TO ROLE {{ role }};
        GRANT SELECT ON ALL TABLES IN SCHEMA {{ database }}.{{ schema }} TO ROLE {{ role }};
        GRANT SELECT ON ALL VIEWS IN SCHEMA {{ database }}.{{ schema }} TO ROLE {{ role }};
      {% endset %}

      {% set grant_future %}
        GRANT SELECT ON FUTURE TABLES IN SCHEMA {{ database }}.{{ schema }} TO ROLE {{ role }};
        GRANT SELECT ON FUTURE VIEWS IN SCHEMA {{ database }}.{{ schema }} TO ROLE {{ role }};
      {% endset %}

      {% do run_query(grant_existing) %}
      {% do run_query(grant_future) %}
      {% do log("Applied schema grants on " ~ database ~ "." ~ schema ~ " to role " ~ role, info=True) %}
    {% endfor %}
  {% endif %}
{% endmacro %}

This macro is best called from an on-run-start hook when you're first setting up a new environment, or as part of your CI/CD pipeline's environment provisioning step. It's not something you want to run on every model — just when schemas are first created or when role memberships change significantly.


On-Run-End Hooks: Revoking Unexpected Access After Each Run

Granting access is only half the problem. The more insidious issue is unexpected access that accumulates over time — a role that was given temporary access for a migration, a service account that shouldn't be reading production marts, or access that was correct six months ago but isn't anymore.

The on-run-end hook runs once after all models complete, making it the right place for a revocation sweep. Here's the architecture: you define the expected set of grants (your source of truth), query Snowflake's information schema for the actual grants, and revoke anything that shouldn't be there.

First, let's create a macro that codifies your expected grants as a data structure:

-- macros/grants/expected_grants.sql

{% macro get_expected_grants() %}
  {# Returns a dict mapping schema -> list of roles that should have SELECT access #}
  {% set expected = {
    'ANALYTICS.MARTS_FINANCE': ['ANALYST_ROLE', 'FINANCE_ANALYST_ROLE', 'LOOKER_SERVICE_ROLE'],
    'ANALYTICS.MARTS_PRODUCT': ['ANALYST_ROLE', 'LOOKER_SERVICE_ROLE', 'DATA_SCIENCE_ROLE'],
    'ANALYTICS.MARTS_EXECUTIVE': ['EXEC_ANALYST_ROLE', 'LOOKER_SERVICE_ROLE'],
    'ANALYTICS.STAGING': ['DATA_SCIENCE_ROLE'],
    'ANALYTICS.INTERMEDIATE': ['DATA_SCIENCE_ROLE', 'DBT_CI_ROLE']
  } %}
  {{ return(expected) }}
{% endmacro %}

Now the on-run-end hook calls a revocation checker:

-- macros/grants/revoke_unexpected_grants.sql

{% macro revoke_unexpected_grants() %}
  {% if execute %}
    {% set expected = get_expected_grants() %}

    {# Query actual grants from Snowflake information schema #}
    {% set actual_grants_query %}
      SELECT
        TABLE_CATALOG || '.' || TABLE_SCHEMA AS full_schema,
        TABLE_NAME,
        GRANTEE,
        PRIVILEGE_TYPE
      FROM ANALYTICS.INFORMATION_SCHEMA.OBJECT_PRIVILEGES
      WHERE
        OBJECT_TYPE IN ('TABLE', 'VIEW')
        AND PRIVILEGE_TYPE = 'SELECT'
        AND GRANTEE NOT IN ('DBT_PROD_ROLE', 'SYSADMIN', 'ACCOUNTADMIN')
        AND TABLE_CATALOG = 'ANALYTICS'
    {% endset %}

    {% set actual_grants = run_query(actual_grants_query) %}

    {% for row in actual_grants.rows %}
      {% set schema_key = row[0] | upper %}
      {% set grantee = row[2] | upper %}

      {% if schema_key in expected %}
        {% set allowed_roles = expected[schema_key] | map('upper') | list %}
        {% if grantee not in allowed_roles %}
          {% set revoke_sql %}
            REVOKE SELECT ON {{ row[0] }}.{{ row[1] }} FROM ROLE {{ grantee }}
          {% endset %}
          {% do run_query(revoke_sql) %}
          {% do log("REVOKED SELECT on " ~ row[0] ~ "." ~ row[1] ~ " from role " ~ grantee ~ " (not in expected grants)", info=True) %}
        {% endif %}
      {% endif %}
    {% endfor %}
  {% endif %}
{% endmacro %}

Register this in dbt_project.yml as an on-run-end hook:

# dbt_project.yml

on-run-end:
  - "{{ revoke_unexpected_grants() }}"

Warning

Be careful about running revocation sweeps in development environments where teammates might have added temporary grants for debugging. Consider gating the revocation macro behind an environment check: {% if target.name == 'prod' %}. Also, test your expected grants dictionary thoroughly before activating this in production — an incorrect entry will silently revoke legitimate access.


Building a Permission Audit Log in Snowflake

Knowing that grants are automated is useful. Having a queryable record of every grant and revocation that ever happened — with timestamps and the dbt run ID that triggered it — is what actually satisfies your data governance requirements. This is especially important if your organization falls under SOC 2, HIPAA, or GDPR compliance frameworks.

Let's build that audit log as a dbt model that gets populated by our grant macros.

First, create the audit table (this is a one-time setup, done outside dbt or in a pre-hook on a seeded model):

CREATE TABLE IF NOT EXISTS ANALYTICS.GOVERNANCE.GRANT_AUDIT_LOG (
  event_id          VARCHAR DEFAULT UUID_STRING(),
  event_timestamp   TIMESTAMP_NTZ DEFAULT CURRENT_TIMESTAMP(),
  event_type        VARCHAR,          -- 'GRANT' or 'REVOKE'
  object_type       VARCHAR,          -- 'TABLE', 'VIEW', 'SCHEMA'
  object_name       VARCHAR,          -- fully qualified object name
  grantee_role      VARCHAR,
  privilege         VARCHAR,
  dbt_run_id        VARCHAR,          -- from env var or dbt invocation metadata
  dbt_target        VARCHAR,
  initiated_by      VARCHAR           -- the Snowflake role that executed the grant
);

Now enhance the grant macro to write audit records:

{% macro grant_select_to_roles(roles, relation=this) %}
  {% if execute %}
    {% set dbt_run_id = env_var('DBT_RUN_ID', 'manual') %}
    {% set dbt_target = target.name %}

    {% for role in roles %}
      {% set grant_sql %}
        GRANT SELECT ON {{ relation }} TO ROLE {{ role }}
      {% endset %}
      {% do run_query(grant_sql) %}

      {% set audit_sql %}
        INSERT INTO ANALYTICS.GOVERNANCE.GRANT_AUDIT_LOG
          (event_type, object_type, object_name, grantee_role, privilege, dbt_run_id, dbt_target, initiated_by)
        VALUES (
          'GRANT',
          'TABLE',
          '{{ relation }}',
          '{{ role }}',
          'SELECT',
          '{{ dbt_run_id }}',
          '{{ dbt_target }}',
          CURRENT_ROLE()
        )
      {% endset %}
      {% do run_query(audit_sql) %}
      {% do log("Granted SELECT on " ~ relation ~ " to role " ~ role, info=True) %}
    {% endfor %}
  {% endif %}
{% endmacro %}

Pass the DBT_RUN_ID as an environment variable from your orchestrator. If you're using Airflow to orchestrate dbt (covered in depth in Orchestrating dbt Runs with Airflow), you can set this per-run with the Airflow run ID:

# In your Airflow DAG
dbt_run_task = BashOperator(
    task_id='dbt_run',
    bash_command=f'DBT_RUN_ID={{"{{ run_id }}"}} dbt run --target prod',
    dag=dag
)

Tip

Snowflake's QUERY_HISTORY view in SNOWFLAKE.ACCOUNT_USAGE captures every DDL statement including GRANTs, but it has a 45-minute latency and a 365-day retention limit. Your custom audit log gives you immediate queryability, structured context (like which dbt run triggered the grant), and indefinite retention. Use both — the native history for forensics, your log for operational reporting.

Now you can query the audit log for compliance reporting:

-- Who was granted access to our finance mart in the last 30 days?
SELECT
  event_timestamp,
  event_type,
  object_name,
  grantee_role,
  dbt_run_id,
  dbt_target
FROM ANALYTICS.GOVERNANCE.GRANT_AUDIT_LOG
WHERE
  object_name ILIKE '%MARTS_FINANCE%'
  AND event_timestamp >= DATEADD('day', -30, CURRENT_TIMESTAMP())
ORDER BY event_timestamp DESC;

This kind of queryable audit trail is a core component of mature data governance — you're not just controlling access, you're creating evidence that your controls worked.


Post-Deploy Scripts: Grants That Run After dbt Completes

Some permissions don't belong inside dbt's model lifecycle at all. Schema-level USAGE grants, warehouse access grants, database-level grants, and role-to-role inheritance adjustments all need to happen once per deployment, not once per model. These are best handled by a post-deploy script that runs after dbt run or dbt build completes.

This script can be a Python file that uses the Snowflake connector, or a shell script calling Snowflake's SnowSQL CLI. Here's a Python-based version that's easy to integrate into your CI/CD pipeline:

# scripts/post_deploy_grants.py

import os
import snowflake.connector
from datetime import datetime

def get_connection():
    return snowflake.connector.connect(
        account=os.environ['SNOWFLAKE_ACCOUNT'],
        user=os.environ['SNOWFLAKE_USER'],
        private_key_file=os.environ['SNOWFLAKE_PRIVATE_KEY_PATH'],
        role='SECURITYADMIN',
        warehouse='DEPLOY_WH'
    )

SCHEMA_GRANTS = {
    'ANALYTICS.MARTS_FINANCE': {
        'roles': ['ANALYST_ROLE', 'FINANCE_ANALYST_ROLE', 'LOOKER_SERVICE_ROLE'],
        'privileges': ['SELECT']
    },
    'ANALYTICS.MARTS_PRODUCT': {
        'roles': ['ANALYST_ROLE', 'LOOKER_SERVICE_ROLE', 'DATA_SCIENCE_ROLE'],
        'privileges': ['SELECT']
    },
    'ANALYTICS.STAGING': {
        'roles': ['DATA_SCIENCE_ROLE'],
        'privileges': ['SELECT']
    }
}

def apply_future_grants(cursor, schema_full, roles, privileges):
    """Apply FUTURE grants so new objects are automatically accessible."""
    db, schema = schema_full.split('.')
    for role in roles:
        for privilege in privileges:
            for obj_type in ['TABLES', 'VIEWS']:
                sql = f"""
                    GRANT {privilege} ON FUTURE {obj_type} 
                    IN SCHEMA {schema_full} 
                    TO ROLE {role}
                """
                cursor.execute(sql)
                print(f"[{datetime.utcnow()}] Future grant: {privilege} on {obj_type} "
                      f"in {schema_full} → {role}")

def apply_existing_grants(cursor, schema_full, roles, privileges):
    """Apply grants to all currently existing objects in the schema."""
    for role in roles:
        for privilege in privileges:
            for obj_type in ['TABLES', 'VIEWS']:
                sql = f"""
                    GRANT {privilege} ON ALL {obj_type} 
                    IN SCHEMA {schema_full} 
                    TO ROLE {role}
                """
                cursor.execute(sql)
                print(f"[{datetime.utcnow()}] Existing grant: {privilege} on all {obj_type} "
                      f"in {schema_full} → {role}")

def apply_usage_grants(cursor, schema_full, roles):
    """Grant USAGE on schema and database, required before SELECT works."""
    db, schema = schema_full.split('.')
    for role in roles:
        cursor.execute(f"GRANT USAGE ON DATABASE {db} TO ROLE {role}")
        cursor.execute(f"GRANT USAGE ON SCHEMA {schema_full} TO ROLE {role}")
        print(f"[{datetime.utcnow()}] USAGE grant: {schema_full} → {role}")

def main():
    conn = get_connection()
    cursor = conn.cursor()

    try:
        for schema_full, config in SCHEMA_GRANTS.items():
            roles = config['roles']
            privileges = config['privileges']
            
            apply_usage_grants(cursor, schema_full, roles)
            apply_existing_grants(cursor, schema_full, roles, privileges)
            apply_future_grants(cursor, schema_full, roles, privileges)

        conn.commit()
        print(f"\n[{datetime.utcnow()}] Post-deploy grants completed successfully.")
    except Exception as e:
        print(f"ERROR during post-deploy grants: {e}")
        raise
    finally:
        cursor.close()
        conn.close()

if __name__ == '__main__':
    main()

This script connects as SECURITYADMIN (which should not be your dbt service role), applies USAGE grants on databases and schemas, then applies both existing and future object grants. It's idempotent — running it twice doesn't break anything, Snowflake just no-ops duplicate grants.

Integrate it into your CI/CD pipeline after the dbt run step. If you're using a system like GitHub Actions or GitLab CI alongside your CI/CD deployment automation:

# .github/workflows/deploy.yml (excerpt)

jobs:
  deploy:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3

      - name: Run dbt build
        run: dbt build --target prod
        env:
          DBT_RUN_ID: ${{ github.run_id }}

      - name: Run post-deploy permission script
        run: python scripts/post_deploy_grants.py
        env:
          SNOWFLAKE_ACCOUNT: ${{ secrets.SNOWFLAKE_ACCOUNT }}
          SNOWFLAKE_USER: ${{ secrets.SNOWFLAKE_DEPLOY_USER }}
          SNOWFLAKE_PRIVATE_KEY_PATH: /tmp/snowflake_key.p8

Note

Use key-pair authentication (not username/password) for your deployment service accounts. This is easier to rotate, works better with secrets managers like AWS Secrets Manager or HashiCorp Vault, and can be scoped to specific roles. Never hardcode credentials in your post-deploy scripts — always pull from environment variables injected by your CI/CD platform.


Handling the dbt `grants` Config Block (dbt Core 1.2+)

Starting with dbt Core 1.2, there's a first-class grants configuration block that handles the common case of SELECT grants to roles. This is worth knowing about, though it has important limitations compared to the macro-based approach.

# dbt_project.yml

models:
  your_project:
    marts:
      finance:
        +grants:
          select: ['ANALYST_ROLE', 'FINANCE_ANALYST_ROLE', 'LOOKER_SERVICE_ROLE']

Or inline in a model config:

{{
  config(
    materialized='table',
    grants={
      'select': ['ANALYST_ROLE', 'FINANCE_ANALYST_ROLE']
    }
  )
}}

The native grants block is appealing for its simplicity, but understand what it does and doesn't do:

It does:

  • Apply grants after model creation (including after full-refresh replacements)
  • Revoke grants from roles that were previously listed but have been removed from the config
  • Work correctly with incremental models and views

It doesn't:

  • Apply schema-level USAGE grants (you still need those)
  • Apply FUTURE grants for schema-wide coverage
  • Write to an audit log
  • Handle conditional grants based on model metadata or environment
  • Let you customize the grant SQL beyond SELECT

For simple projects or early-stage data platforms, the native grants config is a great starting point. For teams with complex role hierarchies, compliance requirements, or multi-environment setups, the macro-based approach gives you far more control. Many teams use both: the native grants config for day-to-day model-level grants, with a post-deploy script handling schema-level setup and future grants.


Hands-On Exercise

Let's build a complete, working version of this system in your dbt project. This exercise assumes you have a Snowflake-backed dbt project with at least a staging and marts layer.

Step 1: Create the audit log table

Run this in Snowflake directly (as SYSADMIN or SECURITYADMIN):

CREATE SCHEMA IF NOT EXISTS ANALYTICS.GOVERNANCE;

CREATE TABLE IF NOT EXISTS ANALYTICS.GOVERNANCE.GRANT_AUDIT_LOG (
  event_id          VARCHAR DEFAULT UUID_STRING(),
  event_timestamp   TIMESTAMP_NTZ DEFAULT CURRENT_TIMESTAMP(),
  event_type        VARCHAR,
  object_type       VARCHAR,
  object_name       VARCHAR,
  grantee_role      VARCHAR,
  privilege         VARCHAR,
  dbt_run_id        VARCHAR,
  dbt_target        VARCHAR,
  initiated_by      VARCHAR
);

-- Grant INSERT to your dbt service role
GRANT INSERT ON TABLE ANALYTICS.GOVERNANCE.GRANT_AUDIT_LOG TO ROLE DBT_PROD_ROLE;
GRANT SELECT ON TABLE ANALYTICS.GOVERNANCE.GRANT_AUDIT_LOG TO ROLE ANALYST_ROLE;

Step 2: Create the grant macro

Create macros/grants/grant_select_to_roles.sql with the audit-logging version shown earlier in this lesson.

Step 3: Configure directory-level post-hooks

Update your dbt_project.yml to apply grants at the folder level, matching your actual role names:

models:
  your_project:
    staging:
      +post_hook: "{{ grant_select_to_roles(['DATA_SCIENCE_ROLE']) }}"
    marts:
      +post_hook: "{{ grant_select_to_roles(['ANALYST_ROLE', 'LOOKER_SERVICE_ROLE']) }}"

Step 4: Run dbt and verify

export DBT_RUN_ID="exercise-run-001"
dbt run --target prod --select marts

After the run, check that grants were applied:

-- Verify grants were created
SHOW GRANTS ON TABLE ANALYTICS.MARTS.YOUR_TABLE_NAME;

-- Verify audit log was populated
SELECT * FROM ANALYTICS.GOVERNANCE.GRANT_AUDIT_LOG
ORDER BY event_timestamp DESC
LIMIT 20;

Step 5: Test full-refresh resilience

Manually grant a role that shouldn't have access:

GRANT SELECT ON TABLE ANALYTICS.MARTS.YOUR_TABLE_NAME TO ROLE TEMP_ANALYST_ROLE;

Now run with full-refresh:

dbt run --target prod --select marts.your_table --full-refresh

Check the grants again — TEMP_ANALYST_ROLE should be gone (the table was replaced), and only the roles in your post-hook should appear. This demonstrates exactly why automated post-hooks beat manual grants.


Common Mistakes & Troubleshooting

"My macro runs but Snowflake throws 'Insufficient privileges' on the GRANT statement."

Your dbt service role needs MANAGE GRANTS privilege, or it needs to be granted the specific privilege WITH GRANT OPTION. For example:

-- As SECURITYADMIN:
GRANT MANAGE GRANTS ON ACCOUNT TO ROLE DBT_PROD_ROLE;
-- OR more narrowly:
GRANT SELECT ON FUTURE TABLES IN SCHEMA ANALYTICS.MARTS 
TO ROLE ANALYST_ROLE 
GRANTED BY DBT_PROD_ROLE;  -- This syntax isn't standard; use MANAGE GRANTS

The cleanest solution: give DBT_PROD_ROLE the MANAGE GRANTS privilege. It's broad, but your dbt service role should already be a trusted infrastructure role.

"My post-hooks run, but roles still can't query the tables."

Almost always a missing USAGE grant. Users can't SELECT from a table if their role doesn't have USAGE on the database AND schema that contain it. Add USAGE grants to your post-deploy script, as shown in the Python script above.

"The revocation macro is revoking access from roles that should have it."

Your expected_grants dictionary has a schema key mismatch. Snowflake stores schema names in uppercase; ensure your dictionary keys are uppercase and match the exact DATABASE.SCHEMA pattern. Add a debug query to print the actual grants before the revocation logic runs:

-- Paste this into Snowflake directly to see what the information schema returns
SELECT TABLE_CATALOG || '.' || TABLE_SCHEMA AS full_schema, GRANTEE, PRIVILEGE_TYPE
FROM ANALYTICS.INFORMATION_SCHEMA.OBJECT_PRIVILEGES
WHERE OBJECT_TYPE = 'TABLE'
LIMIT 50;

Compare the full_schema values to your dictionary keys exactly.

"The grants config block isn't revoking stale access after I remove a role from the list."

The native dbt grants block only issues revokes when it can determine what was previously granted. If you switched from post-hooks to the native grants config, dbt doesn't have history of the hook-based grants and won't revoke them. Run the revocation macro manually or use SHOW GRANTS ON TABLE and issue REVOKEs explicitly for the transition period.

"My on-run-end hook fires even when dbt runs partially (some models failed)."

That's correct behavior — on-run-end fires whether the run succeeded or failed. Use the results context variable available in on-run-end hooks to skip revocation when too many models failed:

{% macro revoke_unexpected_grants() %}
  {% if execute %}
    {% set failed_count = results | selectattr('status', 'equalto', 'error') | list | length %}
    {% if failed_count > 5 %}
      {% do log("Skipping revocation sweep: " ~ failed_count ~ " models failed. Manual review required.", info=True) %}
    {% else %}
      {# ... rest of revocation logic ... #}
    {% endif %}
  {% endif %}
{% endmacro %}

Tip

When debugging hook failures, run with --debug flag: dbt run --debug --select your_model. This prints every SQL statement dbt executes, including hook statements, with the full resolved Jinja output. You'll immediately see what SQL was actually sent to Snowflake.


Summary & Next Steps

You've built an end-to-end automated permission system that lives inside your dbt project. Here's what you now have:

  • Model-level post-hooks that grant SELECT to the right roles immediately after each model is materialized — including after full-refresh runs that would silently destroy manually-applied grants
  • Directory-level grant configs in dbt_project.yml that make permission inheritance automatic for new models added to the right folder
  • A centralized grant macro that wraps every grant in an audit log entry, giving you a queryable record of every access change tied to a specific dbt run
  • A revocation sweep running on-run-end that enforces your expected grant state and removes access that doesn't belong
  • A post-deploy Python script that handles schema-level USAGE grants and future object grants outside dbt's model lifecycle

The core insight to carry forward: permissions aren't a separate concern from your data models. They're a property of the objects you create, and they should live alongside the code that creates those objects, in version control, deployed through the same CI/CD pipeline.

Where to go next:

  • Row-level security and column masking are the next layer of complexity — once you've controlled who can see which tables, you need to control what rows and columns they see within those tables. The row-level security and column masking lesson covers Snowflake's dynamic data masking policies and row access policies.
  • Extend your audit log into a full data lineage story by connecting grant activity to multi-hop lineage tracking, so you know not just who can access a table but what upstream data feeds into it.
  • Add data quality gates before grants fire — there's no point granting analyst access to a mart that just failed its freshness check. Combine the patterns in this lesson with dbt tests and data quality checks to conditionally skip post-hooks when model tests fail.
  • For self-serve analytics platforms, the governed access you've built here is a prerequisite for safely deploying a self-serve analytics platform with dbt Exposures and a semantic layer — you need to trust your permission model before you open the doors to self-serve.
Work With Us

From insight to implementation

Reading is the start. When you're ready to build the data, automation, or AI systems behind it, our team turns strategy into shipped results.

Let's Build

Modern Data Stack

Previous

Snowflake Stages and File Formats: Loading Data from S3, GCS, and Azure Blob into Your Warehouse

Related Insights

Data EngineeringPractitioner

Orchestrating Multi-Step Transformation Pipelines with Makefile and Shell Scripts: Lightweight Automation Without a Full Orchestration Framework

22 min
Data EngineeringFoundation

Snowflake Stages and File Formats: Loading Data from S3, GCS, and Azure Blob into Your Warehouse

16 min
Data EngineeringFoundation

Connecting to and Authenticating with Common Data Sources: Databases, APIs, and Cloud Storage for Pipeline Beginners

16 min

On this page

  • Introduction
  • Prerequisites
  • Understanding the Permission Gap in a Typical dbt Workflow
  • Model-Level Post-Hooks: Granting Access Right After Creation
  • Centralizing Grant Logic with Macros
  • Handling Schema-Level Grants for New Models
  • On-Run-End Hooks: Revoking Unexpected Access After Each Run
  • Building a Permission Audit Log in Snowflake
  • Post-Deploy Scripts: Grants That Run After dbt Completes
  • Handling the dbt `grants` Config Block (dbt Core 1.2+)
  • Hands-On Exercise
  • Common Mistakes & Troubleshooting
  • Summary & Next Steps