Integrating dbt, Snowflake, and Airflow for ETL Workflows

Integrating dbt, Snowflake and Airflow: A Hands-On Guide (2026 Edition)

dbt, Snowflake and Airflow are still one of the most common modern ELT stacks: Snowflake stores and computes, dbt turns raw data into tested models with plain SQL, and Airflow decides when everything runs and what happens when something fails.

I first wrote about this stack in 2024 with my dbt-snowflake-airflow project on GitHub. A lot has changed since: Airflow 3 is now the standard (Airflow 2 reached end of life in April 2026), Astronomer Cosmos has become the usual way to run dbt inside Airflow, and Snowflake is blocking password-only logins for service accounts. This updated guide builds the whole pipeline step by step.

What we will build

  1. An Airflow task loads new order files into a raw Snowflake table.
  2. dbt builds a staging model and a daily revenue model, and runs data tests.
  3. Airflow runs it all daily, with each dbt model as its own task, so you can see, retry and debug models individually.

Who does what:

ToolRole
SnowflakeStorage and compute for raw and modelled data
dbt CoreSQL transformations, tests, documentation and lineage
Apache Airflow 3Scheduling, dependencies, retries and alerting
Astronomer CosmosTurns each dbt model and test into Airflow tasks
Astro CLIRuns Airflow locally in Docker, and deploys to Astronomer

Prerequisites

  • A Snowflake account and a role that can create users, roles and warehouses (or an admin who can run Step 1 for you).
  • Docker Desktop and the Astro CLI installed.
  • Python 3.10+ if you want to run dbt locally as well.

Step 1: Prepare Snowflake (with key-pair authentication)

Pipelines should never log in as a person. Create a dedicated service user that authenticates with a key pair instead of a password. Snowflake has been phasing out single-factor password logins through 2026, and dbt’s own docs ask you to move connections to key-pair or OAuth.

First, generate a key pair on your machine:

openssl genrsa 2048 | openssl pkcs8 -topk8 -inform PEM -out rsa_key.p8 -nocrypt
openssl rsa -in rsa_key.p8 -pubout -out rsa_key.pub

Then create the warehouse, database, role and service user in Snowflake. Paste the public key without the BEGIN and END lines:

USE ROLE ACCOUNTADMIN;

CREATE WAREHOUSE IF NOT EXISTS transform_wh
  WAREHOUSE_SIZE = 'XSMALL' AUTO_SUSPEND = 60 AUTO_RESUME = TRUE;

CREATE DATABASE IF NOT EXISTS analytics;
CREATE SCHEMA  IF NOT EXISTS analytics.raw;

CREATE ROLE IF NOT EXISTS transformer;
GRANT USAGE ON WAREHOUSE transform_wh TO ROLE transformer;
GRANT USAGE, CREATE SCHEMA ON DATABASE analytics TO ROLE transformer;
GRANT ALL ON SCHEMA analytics.raw TO ROLE transformer;

CREATE USER IF NOT EXISTS dbt_svc
  TYPE              = SERVICE
  DEFAULT_ROLE      = transformer
  DEFAULT_WAREHOUSE = transform_wh
  RSA_PUBLIC_KEY    = 'MIIBIjANBgkqh...';

GRANT ROLE transformer TO USER dbt_svc;

-- The raw table our pipeline loads into
CREATE TABLE IF NOT EXISTS analytics.raw.orders (
  order_id     NUMBER,
  customer_id  NUMBER,
  status       STRING,
  amount       NUMBER(12, 2),
  updated_at   TIMESTAMP_NTZ
);

Keep rsa_key.p8 secret. It goes into Airflow’s connection in Step 4 and never into Git.

Step 2: Create the Airflow project

mkdir dbt-snowflake-airflow && cd dbt-snowflake-airflow
astro dev init

This creates an Airflow 3 project. We will put the dbt project inside the dags folder so Airflow can read it:

dbt-snowflake-airflow/
├── Dockerfile
├── requirements.txt
├── .env                      # local secrets, never commit
└── dags/
    ├── orders_pipeline.py    # the Airflow DAG
    └── dbt/
        └── shop/             # the dbt project
            ├── dbt_project.yml
            └── models/
                ├── staging/
                │   ├── sources.yml
                │   ├── stg_orders.sql
                │   └── stg_orders.yml
                └── marts/
                    ├── fct_daily_revenue.sql
                    └── fct_daily_revenue.yml

Add the Python packages Airflow needs to requirements.txt:

astronomer-cosmos
apache-airflow-providers-snowflake

Install dbt in its own virtual environment inside the image, so its dependencies never clash with Airflow’s. Add these lines to the end of the Dockerfile that astro dev init created:

RUN python -m venv dbt_venv && \
    . dbt_venv/bin/activate && \
    pip install --no-cache-dir dbt-snowflake && \
    deactivate

Step 3: Build the dbt project

dags/dbt/shop/dbt_project.yml names the project and sets defaults: views for staging, tables for marts.

name: shop
version: "1.0.0"
profile: shop

models:
  shop:
    staging:
      +materialized: view
      +schema: staging
    marts:
      +materialized: table
      +schema: marts

models/staging/sources.yml declares the raw table, with a freshness check that warns if loading has stalled:

version: 2

sources:
  - name: raw
    database: analytics
    schema: raw
    tables:
      - name: orders
        loaded_at_field: updated_at
        freshness:
          warn_after: {count: 24, period: hour}

models/staging/stg_orders.sql cleans the raw data and keeps only the latest version of each order:

with source as (
    select * from {{ source('raw', 'orders') }}
)

select
    order_id,
    customer_id,
    upper(trim(status))  as status,
    amount,
    updated_at
from source
qualify row_number() over (partition by order_id order by updated_at desc) = 1

models/staging/stg_orders.yml adds tests, so bad data stops the pipeline instead of reaching dashboards:

version: 2

models:
  - name: stg_orders
    columns:
      - name: order_id
        data_tests:
          - unique
          - not_null
      - name: status
        data_tests:
          - accepted_values:
              arguments:
                values: ['PLACED', 'SHIPPED', 'DELIVERED', 'CANCELLED']
      - name: amount
        data_tests:
          - not_null

models/marts/fct_daily_revenue.sql is the table the business actually uses:

select
    date_trunc('day', updated_at)  as order_date,
    count(*)                       as orders,
    sum(amount)                    as revenue
from {{ ref('stg_orders') }}
where status <> 'CANCELLED'
group by 1

And models/marts/fct_daily_revenue.yml makes sure each day appears only once:

version: 2

models:
  - name: fct_daily_revenue
    columns:
      - name: order_date
        data_tests:
          - unique
          - not_null

Tip: by default dbt adds custom schemas to your target schema, so +schema: staging becomes something like PUBLIC_STAGING. That is fine for this guide; override the generate_schema_name macro if you want exact names.

Step 4: Connect Airflow to Snowflake

For local development, define the connection in .env (the Astro CLI loads it automatically). Paste your private key with each line break written as \n:

AIRFLOW_CONN_SNOWFLAKE_DEFAULT='{
  "conn_type": "snowflake",
  "login": "DBT_SVC",
  "schema": "PUBLIC",
  "extra": {
    "account": "myorg-myaccount",
    "warehouse": "TRANSFORM_WH",
    "database": "ANALYTICS",
    "role": "TRANSFORMER",
    "private_key_content": "-----BEGIN PRIVATE KEY-----\nMIIE...\n-----END PRIVATE KEY-----\n"
  }
}'

Make sure .env is in .gitignore. In production, keep this connection in a secrets backend such as Azure Key Vault, AWS Secrets Manager or Astro’s environment manager, not in a file.

Step 5: Write the DAG with Cosmos

Cosmos reads your dbt project and creates one Airflow task per model, with its tests attached. It also builds dbt’s profiles.yml for you from the Airflow connection, so credentials live in one place.

dags/orders_pipeline.py:

import os
from datetime import datetime, timedelta

from airflow.sdk import dag
from airflow.providers.common.sql.operators.sql import SQLExecuteQueryOperator
from cosmos import DbtTaskGroup, ExecutionConfig, ProfileConfig, ProjectConfig
from cosmos.profiles import SnowflakePrivateKeyPemProfileMapping

AIRFLOW_HOME = os.environ.get("AIRFLOW_HOME", "/usr/local/airflow")
DBT_PROJECT = f"{AIRFLOW_HOME}/dags/dbt/shop"

profile_config = ProfileConfig(
    profile_name="shop",
    target_name="prod",
    profile_mapping=SnowflakePrivateKeyPemProfileMapping(
        conn_id="snowflake_default",
        profile_args={"database": "ANALYTICS", "schema": "PUBLIC"},
    ),
)


@dag(
    schedule="@daily",
    start_date=datetime(2026, 1, 1),
    catchup=False,
    default_args={"retries": 2, "retry_delay": timedelta(minutes=5)},
    tags=["dbt", "snowflake"],
)
def orders_pipeline():
    load_raw_orders = SQLExecuteQueryOperator(
        task_id="load_raw_orders",
        conn_id="snowflake_default",
        sql="""
            COPY INTO analytics.raw.orders
            FROM @analytics.raw.orders_stage
            FILE_FORMAT = (TYPE = CSV SKIP_HEADER = 1)
            ON_ERROR = 'ABORT_STATEMENT';
        """,
    )

    transform = DbtTaskGroup(
        group_id="dbt_shop",
        project_config=ProjectConfig(DBT_PROJECT),
        profile_config=profile_config,
        execution_config=ExecutionConfig(
            dbt_executable_path=f"{AIRFLOW_HOME}/dbt_venv/bin/dbt",
        ),
        operator_args={"install_deps": True},
    )

    load_raw_orders >> transform


orders_pipeline()

The COPY INTO step assumes a stage called orders_stage pointing at your files. Swap it for whatever loads your raw data: Snowpipe, Openflow, Fivetran or another Airflow operator.

A few details worth knowing:

  • DbtTaskGroup vs DbtDag: use DbtTaskGroup when dbt is one part of a bigger DAG, as here. Use DbtDag when the DAG only runs dbt.
  • Airflow 3 imports: dag now comes from airflow.sdk. On Airflow 2 you would import it from airflow.decorators.
  • Encrypted keys: if your private key has a passphrase, use SnowflakeEncryptedPrivateKeyPemProfileMapping and add the passphrase to the connection.
  • Retries per model: if one model fails, Airflow retries just that task, not the whole dbt run.

Step 6: Run it locally

astro dev start

Open the Airflow UI at http://localhost:8080, unpause orders_pipeline and trigger it. In the graph view you will see load_raw_orders followed by a dbt_shop group containing stg_orders and fct_daily_revenue, each with its tests.

Check the result in Snowflake:

SELECT * FROM analytics.public_marts.fct_daily_revenue ORDER BY order_date DESC;

Step 7: Make it production-ready

  • Make big models incremental. Use materialized='incremental' with a unique_key so daily runs only process new rows instead of rebuilding history.
  • Separate dev and prod. Use different Snowflake databases or schemas and separate Airflow connections, and point the target_name accordingly.
  • Alert on failure. Add an on_failure_callback that posts to Teams, Slack or email.
  • Test in CI. Run dbt build against a dev schema on every pull request before changes reach Airflow.
  • Watch costs. Give the pipeline its own warehouse with a 60-second auto-suspend and a resource monitor, so it is easy to track. My Snowflake cost optimisation playbook covers this in detail.
  • Deploy. With Astronomer, astro deploy pushes the same project to a managed Airflow deployment.

Troubleshooting

ProblemLikely cause and fix
JWT token is invalidThe public key on the Snowflake user does not match the private key, or the account identifier is wrong. Re-run ALTER USER dbt_svc SET RSA_PUBLIC_KEY = '...' and check the account is in orgname-accountname format.
dbt executable not foundThe virtual environment path in ExecutionConfig does not match the Dockerfile. Restart with astro dev restart after changing the Dockerfile.
Insufficient privileges to operate on schemaThe transformer role needs CREATE SCHEMA on the database so dbt can create its staging and marts schemas.
DAG does not appear in the UICheck the DAG import errors at the top of the Airflow UI. A missing package in requirements.txt is the usual cause.

Do you still need Airflow?

Since 2026, dbt Projects on Snowflake can run dbt natively inside Snowflake, with Slim CI, deferral and failure recovery now generally available. If your pipeline is only dbt plus simple scheduling, that may be all you need. Keep Airflow when you orchestrate across many systems: ingestion tools, APIs, machine learning jobs and notifications in one place. I cover both options in what’s new in Snowflake in 2026.

Wrapping up

With Cosmos, dbt models become first-class Airflow tasks, Snowflake credentials live in one secure connection, and tests stop bad data early. Start with the small pipeline above, then grow it model by model.

The original project is on GitHub: ajay054/dbt-snowlfake-airflow.

Further reading

1 Comment

Leave a Reply

Your comment appears after we check it.