diff --git a/airflow-dbt-transformation/Makefile b/airflow-dbt-transformation/Makefile index b3bfaef..6d738a0 100644 --- a/airflow-dbt-transformation/Makefile +++ b/airflow-dbt-transformation/Makefile @@ -1,5 +1,5 @@ AIRFLOW_CONTAINER = localstack-mwaa-000000000000-us-east-1-my-mwaa-env -# the versions in requirements.txt are pinned to match this Airflow version +# the constraints file in requirements.txt is the one of this Airflow version AIRFLOW_VERSION = 3.0.6 usage: ## Shows usage for this Makefile diff --git a/airflow-dbt-transformation/README.md b/airflow-dbt-transformation/README.md index 85c178e..c6fff55 100644 --- a/airflow-dbt-transformation/README.md +++ b/airflow-dbt-transformation/README.md @@ -38,12 +38,18 @@ From your machine, connect to `snowflake.localhost.localstack.cloud` on port 456 The sample application provides Makefile targets to simplify the setup process. -Run the following command to initialize the Airflow environment in LocalStack (this may take a couple of seconds). It uploads `requirements.txt` first, so the environment installs `astronomer-cosmos`, `dbt-snowflake` and the Snowflake provider: +Run the following command to initialize the Airflow environment in LocalStack (this may take a couple of seconds). It uploads `requirements.txt` first, so the environment installs `astronomer-cosmos` and the Snowflake provider: ``` make init ``` -The environment runs Airflow 3.0.6 (`AIRFLOW_VERSION` in the `Makefile`), and `requirements.txt` pins `apache-airflow` and the other packages to versions that match it. Keep the two in sync: without the pins, `pip` upgrades Airflow itself while installing dbt, and the Airflow services then fail to start with `Database migration required`. To use another Airflow version, change `AIRFLOW_VERSION` and take the pins from the [constraints file](https://airflow.apache.org/docs/apache-airflow/stable/installation/installing-from-pypi.html#constraints-files) of that version. +Airflow and dbt do not share a Python environment, because their dependencies conflict (dbt needs newer `protobuf` and Snowflake connector versions than Airflow 3.0.6 allows): + +- `requirements.txt` lists only what Airflow imports to load the DAG. It has no version pins. Its first line applies the [constraints file](https://airflow.apache.org/docs/apache-airflow/stable/installation/installing-from-pypi.html#constraints-files) of the environment's Airflow version, so `pip` cannot upgrade Airflow or the packages its image ships. +- dbt runs in its own virtual environment. The DAG uses the Cosmos [virtualenv execution mode](https://astronomer.github.io/astronomer-cosmos/getting_started/execution-modes.html#virtualenv): the first dbt task creates `/opt/airflow/dbt_venv` and installs the newest `dbt-snowflake` into it, and the following tasks reuse it. To use a specific dbt version, set it in `dbt_requirements` in `airflow_dag.py`. +- Airflow's own environment has no dbt, so Cosmos cannot run `dbt ls` to render the DAG. The DAG sets `LoadMode.CUSTOM`, which reads the models and their `ref()` calls with the Cosmos parser. + +The environment runs Airflow 3.0.6 (`AIRFLOW_VERSION` in the `Makefile`) on Python 3.12. To use another Airflow version, change `AIRFLOW_VERSION` and the two versions in the constraints URL in `requirements.txt`. After deploying the Airflow environment, you should be able to request its details, and extract the webserver URL: ``` diff --git a/airflow-dbt-transformation/airflow_dag.py b/airflow-dbt-transformation/airflow_dag.py index 57395ae..d00cd6f 100644 --- a/airflow-dbt-transformation/airflow_dag.py +++ b/airflow-dbt-transformation/airflow_dag.py @@ -1,6 +1,5 @@ import json import os -import shutil from datetime import datetime from pathlib import Path @@ -9,7 +8,8 @@ from airflow.providers.standard.operators.empty import EmptyOperator except ImportError: # Airflow 2 from airflow.operators.empty import EmptyOperator -from cosmos import DbtTaskGroup, ProjectConfig, ProfileConfig, ExecutionConfig +from cosmos import DbtTaskGroup, ProjectConfig, ProfileConfig, ExecutionConfig, RenderConfig +from cosmos.constants import ExecutionMode, LoadMode from cosmos.profiles.snowflake.user_pass import SnowflakeUserPasswordProfileMapping from snowflake import connector @@ -55,10 +55,12 @@ target_name="dev", profile_mapping=credentials) -# use a dedicated dbt virtualenv if the environment has one, otherwise the dbt -# installed from requirements.txt -dbt_venv_executable = f"{os.environ['AIRFLOW_HOME']}/dbt_venv/bin/dbt" -dbt_executable = dbt_venv_executable if os.path.exists(dbt_venv_executable) else shutil.which("dbt") +# dbt runs in its own virtual environment, so its dependencies cannot conflict +# with the packages of Airflow. Cosmos creates the environment in the first dbt +# task, installs the newest dbt-snowflake (which brings dbt-core) and reuses it +# in the following tasks. +dbt_venv_dir = Path(os.environ["AIRFLOW_HOME"]) / "dbt_venv" +dbt_requirements = ["dbt-snowflake"] @dag(schedule="@hourly", @@ -73,8 +75,14 @@ def dbt_snowpark_dag(): group_id="transform_data", project_config=ProjectConfig(dbt_project_path), profile_config=profile_config, - execution_config=ExecutionConfig(dbt_executable_path=dbt_executable), - operator_args={"install_deps": True}, + execution_config=ExecutionConfig( + execution_mode=ExecutionMode.VIRTUALENV, + virtualenv_dir=dbt_venv_dir, + ), + # Airflow's own environment has no dbt, so read the models and their + # ref() dependencies with the Cosmos parser instead of `dbt ls` + render_config=RenderConfig(load_method=LoadMode.CUSTOM), + operator_args={"install_deps": True, "py_requirements": dbt_requirements}, ) intermediate = EmptyOperator(task_id='intermediate') diff --git a/airflow-dbt-transformation/dbt_project.yml b/airflow-dbt-transformation/dbt_project.yml index 2ab42e1..020ce5a 100644 --- a/airflow-dbt-transformation/dbt_project.yml +++ b/airflow-dbt-transformation/dbt_project.yml @@ -3,16 +3,16 @@ models: test_dbt: # Applies to all files under models/example/ transform: - schema: transform - materialized: view + +schema: transform + +materialized: view analysis: - schema: analysis - materialized: view + +schema: analysis + +materialized: view seeds: bookings_1: - enabled: true + +enabled: true bookings_2: - enabled: true + +enabled: true customers: - enabled: true + +enabled: true diff --git a/airflow-dbt-transformation/requirements.txt b/airflow-dbt-transformation/requirements.txt index 76af33b..20c383d 100644 --- a/airflow-dbt-transformation/requirements.txt +++ b/airflow-dbt-transformation/requirements.txt @@ -1,15 +1,9 @@ -# The environment runs Airflow 3.0.6 on Python 3.12 (`--airflow-version` in the -# Makefile). Pin Airflow and the packages its image already ships, so that -# installing dbt cannot upgrade Airflow itself: an upgraded Airflow no longer -# matches the environment's metadata database and fails to start. -# The first three versions are the ones in the Airflow constraints file: -# https://raw.githubusercontent.com/apache/airflow/constraints-3.0.6/constraints-3.12.txt -# That file cannot be used as `--constraint` here, because dbt needs newer -# protobuf and isodate versions than it allows. -apache-airflow==3.0.6 -apache-airflow-providers-snowflake==6.4.0 -snowflake-connector-python==3.17.2 -astronomer-cosmos==1.16.0 -# the newest dbt releases that work with snowflake-connector-python 3.x -dbt-core==1.10.23 -dbt-snowflake==1.10.5 +# What Airflow itself imports to load and run the DAG. dbt is not in this list: +# Cosmos installs it into a separate virtual environment (see airflow_dag.py). +# The constraints file of the environment's Airflow and Python version +# (`AIRFLOW_VERSION` in the Makefile, Python 3.12) keeps `pip` from upgrading +# Airflow or the packages its image ships. +--constraint https://raw.githubusercontent.com/apache/airflow/constraints-3.0.6/constraints-3.12.txt +apache-airflow-providers-snowflake +snowflake-connector-python +astronomer-cosmos diff --git a/airflow-dbt-transformation/test.sh b/airflow-dbt-transformation/test.sh index 73a2943..059d2ee 100755 --- a/airflow-dbt-transformation/test.sh +++ b/airflow-dbt-transformation/test.sh @@ -25,7 +25,7 @@ poll() { airflow() { docker exec "$CONTAINER" airflow "$@" 2>/dev/null; } diagnostics() { docker inspect "$CONTAINER" --format '{{json .NetworkSettings.Networks}}' | jq -c 'keys' || true - docker exec "$CONTAINER" bash -c 'ls -la /opt/airflow/dags; pip show apache-airflow astronomer-cosmos dbt-snowflake 2>&1 | grep -E "^(Name|Version)"' || true + docker exec "$CONTAINER" bash -c 'ls -la /opt/airflow/dags; pip show apache-airflow astronomer-cosmos 2>&1 | grep -E "^(Name|Version)"; $AIRFLOW_HOME/dbt_venv/bin/dbt --version' || true docker exec "$CONTAINER" airflow dags list-import-errors || true docker exec "$CONTAINER" bash -c 'tail -n 40 $(find /opt/airflow/logs -path "*query_result_data*" -name "*.log" | head -1)' || true docker logs --tail 80 "$CONTAINER" 2>&1 | grep -v SyntaxWarning || true @@ -43,7 +43,8 @@ echo "PASS: MWAA environment is available" make deploy dag_synced() { docker exec "$CONTAINER" test -f /opt/airflow/dags/airflow_dag.py -a -d /opt/airflow/dags/macros; } poll "the DAG files to be synced from S3" 30 10 dag_synced -requirements_installed() { docker exec "$CONTAINER" bash -c "pip show astronomer-cosmos dbt-snowflake" > /dev/null 2>&1; } +# dbt is not among them: Cosmos installs it into its own virtual environment in the first dbt task +requirements_installed() { docker exec "$CONTAINER" bash -c "pip show astronomer-cosmos" > /dev/null 2>&1; } poll "the requirements to be installed" 60 10 requirements_installed echo "PASS: DAG files synced and requirements installed" @@ -75,6 +76,18 @@ if [ "$state" != "success" ]; then fi echo "PASS: the dbt seeds, models and the PREPPED_DATA query succeeded" +# dbt ran from its own virtual environment, and installing the requirements left Airflow's environment alone +docker exec "$CONTAINER" bash -c '$AIRFLOW_HOME/dbt_venv/bin/dbt --version' +installed=$(docker exec "$CONTAINER" bash -c "pip list --format json" 2>/dev/null) +airflow_version=$(jq -r '.[] | select(.name == "apache-airflow") | .version' <<< "$installed") +expected_version=$(sed -n 's/^AIRFLOW_VERSION = //p' Makefile) +if [ "$airflow_version" != "$expected_version" ] || jq -e 'any(.[]; .name | startswith("dbt-"))' <<< "$installed" > /dev/null; then + echo "Test failed: expected Airflow $expected_version without dbt in Airflow's environment, found Airflow $airflow_version and:" + jq -r '.[] | select(.name | startswith("dbt-")) | "\(.name) \(.version)"' <<< "$installed" + exit 1 +fi +echo "PASS: Airflow is still $airflow_version and dbt is installed only in the virtual environment" + snow connection add --connection-name airflow-dbt --user test --password test --account test \ --host snowflake.localhost.localstack.cloud --port 4567 --no-interactive > /dev/null 2>&1 || true rows=$(snow sql -c airflow-dbt --format json -q "SELECT COUNT(*) AS N FROM test.transform.PREPPED_DATA" | jq -r '.. | objects | .N? // empty' | head -1)