With prefect-dbt, you can trigger and observe dbt Cloud jobs, execute dbt Core CLI commands, and incorporate other tools, such as Snowflake, into your dbt runs.
Prefect provides a global view of the state of your workflows and allows you to take action based on state changes.
If you have an existing dbt Cloud job, use the pre-built flow run_dbt_cloud_job to trigger a job run and wait until the job run is finished.If some nodes fail, run_dbt_cloud_job efficiently retries the unsuccessful nodes.Prior to running this flow, save your dbt Cloud credentials to a DbtCloudCredentials block:
from prefect import flowfrom prefect_dbt.cloud import DbtCloudJobfrom prefect_dbt.cloud.jobs import run_dbt_cloud_job@flowdef run_dbt_job_flow(): result = run_dbt_cloud_job( dbt_cloud_job=DbtCloudJob.load("my-block-name"), targeted_retries=5, ) return resultrun_dbt_job_flow()
Prefect-dbt supports execution of dbt Core CLI commands.
If you don’t have a DbtCoreOperation block saved, create one and set the commands that you want to run.Optionally, specify the project_dir.
If profiles_dir is not set, the DBT_PROFILES_DIR environment variable will be used.
If DBT_PROFILES_DIR is not set, the default directory will be used $HOME/.dbt/.
These pre-built tasks can also create artifacts. These artifacts have extra information about dbt Core runs, such as messages and compiled code for nodes that fail or have errors.
Use a DbtCliProfile block to create profiles.yml.
Then, specify profiles_dir where profiles.yml will be written.
Here’s example code with placeholders:
from prefect import flowfrom prefect_dbt.cli import DbtCliProfile, DbtCoreOperation@flowdef trigger_dbt_flow(): dbt_cli_profile = DbtCliProfile.load("DBT-CORE-OPERATION-BLOCK-PLACEHOLDER") with DbtCoreOperation( commands=["dbt debug", "dbt run"], project_dir="PROJECT-DIRECTORY-PLACEHOLDER", profiles_dir="PROFILES-DIRECTORY-PLACEHOLDER", dbt_cli_profile=dbt_cli_profile, ) as dbt_operation: dbt_process = dbt_operation.trigger() # do other things before waiting for completion dbt_process.wait_for_completion() result = dbt_process.fetch_result() return resultif __name__ == "__main__": trigger_dbt_flow()
Supplying the dbt_cli_profile argument will overwrite existing profiles.yml filesIf you already have a profiles.yml file in the specified profiles_dir, the file will be overwritten. If you do not specify a profiles directory, profiles.yml at ~/.dbt/ would be overwritten.
Visit the SDK reference in the side navigation to see other built-in TargetConfigs blocks.If the desired service profile is not available, you can build one from the generic TargetConfigs class.
For assistance using dbt, consult the dbt documentation.Refer to the prefect-dbt API documentation linked in the sidebar to explore all the capabilities of the prefect-dbt library.