|
| 1 | +# Base imports |
| 2 | +import os |
| 3 | +import pendulum |
| 4 | +import datetime |
| 5 | + |
| 6 | +# PyPI imports |
| 7 | +import yaml |
| 8 | + |
| 9 | +# Airflow imports |
| 10 | +from airflow.decorators import dag, task |
| 11 | +from airflow.operators.bash import BashOperator |
| 12 | +from airflow.hooks.base import BaseHook |
| 13 | + |
| 14 | +# Dataset name in BigQuery for DBT |
| 15 | +DBT_DATASET = "reporting" |
| 16 | + |
| 17 | + |
| 18 | +@dag( |
| 19 | + schedule="@daily", |
| 20 | + catchup=False, |
| 21 | + start_date=pendulum.datetime(2025, 1, 1), |
| 22 | + dagrun_timeout=datetime.timedelta(minutes=20), |
| 23 | +) |
| 24 | +def DBT(): |
| 25 | + |
| 26 | + # File paths for service account key and dbt profile |
| 27 | + PROFILES_DIR = "/tmp/.dbt" |
| 28 | + KEYFILE_PATH = os.path.join(PROFILES_DIR, "bq-service-account.json") |
| 29 | + PROFILE_PATH = os.path.join(PROFILES_DIR, "dbt_profile.yml") |
| 30 | + |
| 31 | + @task( |
| 32 | + task_id="generate_dbt_profile", |
| 33 | + ) |
| 34 | + def generate_dbt_profile(): |
| 35 | + # Get BigQuery connection details |
| 36 | + conn = BaseHook.get_connection("bigquery_reporting") |
| 37 | + |
| 38 | + # Write keyfile to temporary file |
| 39 | + os.makedirs(os.path.dirname(KEYFILE_PATH), exist_ok=True) |
| 40 | + with open(KEYFILE_PATH, "w") as f: |
| 41 | + f.write(conn.extra_dejson.get("keyfile_dict")) |
| 42 | + |
| 43 | + # Generate profile with BigQuery details |
| 44 | + profile = { |
| 45 | + "michael": { |
| 46 | + "outputs": { |
| 47 | + "dev": { |
| 48 | + "type": "bigquery", |
| 49 | + "method": "service-account", |
| 50 | + "keyfile": KEYFILE_PATH, |
| 51 | + "dataset": DBT_DATASET, |
| 52 | + "project": conn.extra_dejson.get("project"), |
| 53 | + "location": conn.extra_dejson.get("location"), |
| 54 | + "priority": "interactive", |
| 55 | + "job_execution_timeout_seconds": 300, |
| 56 | + "job_retries": 1, |
| 57 | + "threads": 1, |
| 58 | + }, |
| 59 | + }, |
| 60 | + "target": "dev", |
| 61 | + } |
| 62 | + } |
| 63 | + # Create profile file for dbt run |
| 64 | + with open(PROFILE_PATH, "w") as f: |
| 65 | + yaml.dump(profile, f) |
| 66 | + |
| 67 | + dbt_run = BashOperator( |
| 68 | + task_id="dbt_run", |
| 69 | + bash_command=f"dbt run --profiles-dir {PROFILES_DIR}", |
| 70 | + env={"DBT_PROFILES_DIR": PROFILES_DIR}, |
| 71 | + ) |
| 72 | + |
| 73 | + @task( |
| 74 | + task_id="cleanup_files", |
| 75 | + ) |
| 76 | + def cleanup_files(): |
| 77 | + # Remove temporary files |
| 78 | + os.remove(PROFILES_DIR) |
| 79 | + |
| 80 | + # Define DAG workflow |
| 81 | + generate_dbt_profile() >> dbt_run >> cleanup_files() |
0 commit comments