Databricks Field Guide

Operating · Chapter 25

Databricks CI/CD with bundles, Terraform and environments

Reviewed by TechFabric engineers. How we write this guide →

CI/CD on Databricks means every job, pipeline, dashboard and grant is defined in files under version control and deployed from a pipeline, never by clicking in a workspace. Databricks' tool for the project layer is Declarative Automation Bundles (formerly Databricks Asset Bundles), driven by the databricks bundle CLI commands validate, deploy and run against named targets such as dev and prd; the Databricks Terraform provider covers the account and workspace estate underneath.

A data team that deploys by clicking usually knows it, and the reason it hasn't changed is rarely the tooling. This chapter is how we'd set both tools up, what the pipeline should run, and the deployment failures we'd design against, checked against the Databricks CLI 1.x and provider 1.x documentation in October 2026.

The short version

The question this chapter answers is simple to ask and uncomfortable to answer honestly: if your production data platform were deleted this afternoon, could you rebuild it from a code repository, and how long would it take. In most organisations the honest answer involves someone remembering what they configured. That is a risk, and it is also why data changes feel scarier than application changes and therefore happen more slowly. The fix is the same one software teams adopted years ago. Everything that runs is described in files under version control, changes are reviewed and tested automatically, and the same tested artefact is promoted from development to production with only its configuration differing.

Everything that runs is in a repository #

We'd put notebooks, pipeline definitions, job definitions, SQL, cluster policies and grants in version control, and derive the deployed state of a workspace from a commit, never from a person's clicks in a browser. Existing jobs built in the UI don't have to be rewritten by hand: databricks bundle generate job --existing-job-id 123456789 --bind writes the job's definition into the bundle and binds the deployed job to it, so the next deploy updates it rather than creating a copy. It handles jobs with notebook tasks today, and it's the first command we'd run on an estate that has none. Git folders are where engineers edit that code inside the workspace; they're a development surface, and production is deployed from CI rather than from a Git folder.

The test is the one in the plain-language box above, and we'd ask it in the first week. An estate where the honest answer involves phrases like "mostly" or "someone would remember" has a documentation problem disguised as a deployment problem, and it usually surfaces as an inability to create a realistic test environment, which is what keeps the test suite thin.

Bundles for what ships with code #

Declarative Automation Bundles work from one declaration: they describe jobs, pipelines, dashboards, serving endpoints and the other resources a project needs, with per-environment targets, in a databricks.yml at the root of the project. The rename changed nothing you type: the CLI is still databricks bundle and the file is still databricks.yml. What did change underneath is the deployment engine. Bundles now deploy through a direct engine by default rather than through Terraform, Databricks CLI 1.14 and later migrate older bundles on deploy, and CLI 1.20.0 removed the Terraform engine (direct deployment). So we'd pin a current 1.x CLI in CI rather than whatever the build image happens to carry.

A new project starts from a template. databricks bundle init offers default-python, default-sql, default-scala, default-minimal, dbt-sql, pydabs (bundles defined in Python) and mlops-stacks (templates):

databricks bundle init default-python

We'd use bundles for anything that belongs to a project and Terraform for account and workspace topology.

The division is not arbitrary. Workspace topology changes rarely, is owned by a platform team, and has a blast radius spanning projects. Job and pipeline definitions change constantly, are owned by the team that owns the data product, and should ship on that team's cadence.

databricks.ymlyaml
bundle:
  name: originations

variables:
  catalog:
    description: Catalog this deployment writes to
  deploy_sp:
    description: Application ID of the service principal production runs as, passed in by CI
    default: ""

resources:
  jobs:
    daily_load:
      name: originations-daily-load
      schedule:
        quartz_cron_expression: "0 0 5 * * ?"
        timezone_id: "America/Phoenix"
      tasks:
        - task_key: ingest
          notebook_task:
            notebook_path: ./src/ingest.py
            base_parameters:
              catalog: ${var.catalog}

targets:
  dev:
    mode: development
    default: true
    variables:
      catalog: originations_dev
  prd:
    mode: production
    git:
      branch: main
    variables:
      catalog: originations_prd
    run_as:
      service_principal_name: ${var.deploy_sp}

The task names no cluster, so it runs on serverless jobs compute where the workspace has serverless enabled. run_as takes the service principal's application ID, and CI passes it in with --var, so no UUID is pasted into the file and the value is the same one the runner authenticates with.

databricks bundle validate -t dev      # catches a malformed resource before anything deploys
databricks bundle deploy -t dev        # your own prefixed, paused copy
databricks bundle run daily_load -t dev
databricks bundle summary -t dev       # what is deployed, with workspace links
databricks bundle deploy -t prd --var="deploy_sp=$DATABRICKS_CLIENT_ID"   # from CI only

Three settings in that file do more work than they appear to, and each behaviour below is from Databricks' page on deployment modes. mode: development prefixes every deployed resource with [dev <your short name>], pauses all schedules and triggers, and turns off the deployment lock, so ten engineers can deploy the same bundle into one workspace without colliding or firing a production schedule. It also marks pipelines as development pipelines. mode: production checks that any pipelines are not in development mode and that the current Git branch matches the target's git.branch, which is what stops someone deploying production from a feature branch on their laptop. And run_as makes the production deployment execute as a service principal, which Databricks recommends for production and which means the deployment path doesn't leave with a departing engineer.

Where each object belongs is the decision we'd settle in the first week, because an object owned by two tools is changed by both and owned by neither:

Object Owned by Why there
Workspaces, metastore assignment, network, storage credentials Terraform, account-level pipeline Rare changes, platform team, blast radius across every project
Catalogs, account groups, catalog-level grants, cluster and budget policies Terraform, workspace-level pipeline Shared by several products; a grant here is a security decision
Schemas, tables' owners, grants inside one product's schemas The product's bundle, or Terraform if the platform team reviews every grant Changes with the product, but someone must own the review
Jobs, pipelines, dashboards, serving endpoints, quality monitors The product's bundle Change weekly, shipped on the team's cadence
A notebook someone is exploring in Nobody, until it's promoted Exploration that has to be deployed isn't exploration any more

The middle row is the one we'd expect to cause trouble. Bundles can define schemas and their grants, and Terraform's databricks_grants is authoritative for whatever it names, so if both touch the same schema the next terraform apply silently removes what the bundle granted. The singular databricks_grant resource isn't the safe alternative it sounds like: it's authoritative for every grant one principal holds on that securable. Pick one per securable and write it in the repository's README.

A reference topology in code #

It helps to see the division as two bodies of code with two audiences and two release cadences. Terraform owns the account-level estate, which is the set of things that exist before any product does: workspaces, the assignment of a metastore to each of them, the account-level groups that identity federation fills, the cluster policies that constrain what compute may be created, and the catalog grants that decide who reads what. Bundles own what ships with a product, which is jobs, pipelines, and the per-target configuration those need. The sketch below is deliberately partial and is about shapes rather than a working configuration.

infra/estate.tfhcl
terraform {
  required_providers {
    databricks = {
      source  = "databricks/databricks"
      version = "~> 1.139"
    }
  }
}

# Account-level provider configuration (host, account_id, auth) omitted.

resource "databricks_mws_workspaces" "prd" {
  account_id     = var.account_id
  workspace_name = "tf-prd-analytics"
  aws_region     = var.region

  credentials_id           = databricks_mws_credentials.this.credentials_id
  storage_configuration_id = databricks_mws_storage_configurations.this.storage_configuration_id
}

resource "databricks_metastore_assignment" "prd" {
  metastore_id = databricks_metastore.eu_west.id
  workspace_id = databricks_mws_workspaces.prd.workspace_id
}

resource "databricks_group" "originations_readers" {
  display_name = "originations-readers"
}

# Authoritative for this catalog: grants made by hand are reset.
resource "databricks_grants" "originations_prd" {
  catalog = "originations_prd"

  grant {
    principal  = databricks_group.originations_readers.display_name
    privileges = ["USE_CATALOG", "SELECT"]
  }
}

Three things in that file matter. The workspace, the metastore assignment, and the group are all account-level objects, so they are applied with account-level credentials rather than workspace ones, which is a different provider configuration and usually a different pipeline. The group is defined once and holds members that arrive from the identity provider rather than from Terraform, so the code owns the group's existence and its entitlements while the identity provider owns its membership. And the grants resource is authoritative for the securable it names, which is the property that makes it useful and the property that makes it dangerous, as the warning below explains.

The bundle sits in the product repository, and in the file above the job is defined once while the targets change only what genuinely differs, here the catalog. The temptation is to let dev and prd drift into two nearly identical job definitions under targets, and the rule we'd hold a review to is that any field set under both targets becomes a variable instead.

Who may run these is a boundary worth writing down. Terraform is applied by a pipeline rather than by a person, authenticating as an account-level service principal whose credentials no engineer holds, with a plan produced on the pull request and an apply only on merge to the main branch. Bundle deployments to production likewise run as a service principal, which is what the run_as setting above configures, so that the production deployment path does not belong to whoever last deployed and does not leave when they do. Drift is then a scheduled job rather than a discovery: a nightly plan that fails the build when it is non-empty tells you within a day that production no longer matches the repository, which is the only way to find manual changes before they cause a surprise.

What the pipeline actually runs #

A pull request touching data code should trigger, in order, static checks and formatting, unit tests over transformation logic with no cluster involved, a bundle validation that catches malformed resource definitions before anything is deployed, and then a deployment to an isolated development target where integration tests run against real infrastructure with fixture data.

yes

Pull request

Lint and format

Unit tests
no cluster

Bundle validate

Deploy to dev target

Integration tests
fixture data

Approved

Deploy to staging

Deploy to production
as service principal

What happens between a pull request and production

In GitHub Actions the deploy step is short. We'd authenticate the runner as the deployment service principal through workload identity federation, so there's no long-lived secret to rotate: the service principal carries a GitHub federation policy whose subject matches the repository and environment, and the CLI reads DATABRICKS_AUTH_TYPE: github-oidc (GitHub Actions).

.github/workflows/deploy-prd.ymlyaml
name: deploy-prd
on:
  push:
    branches: [main]

permissions:
  id-token: write   # required for workload identity federation
  contents: read

jobs:
  deploy:
    runs-on: ubuntu-latest
    environment: Prod
    env:
      DATABRICKS_AUTH_TYPE: github-oidc
      DATABRICKS_HOST: ${{ vars.DATABRICKS_HOST }}
      DATABRICKS_CLIENT_ID: ${{ secrets.DATABRICKS_CLIENT_ID }}
    steps:
      - uses: actions/checkout@v4
      - uses: databricks/setup-cli@main
      - run: databricks bundle validate -t prd --var="deploy_sp=$DATABRICKS_CLIENT_ID"
      - run: databricks bundle deploy -t prd --var="deploy_sp=$DATABRICKS_CLIENT_ID"

The unit test layer is the one we'd expect a data team to have skipped, and it pays back fastest. It depends on a single structural decision: transformation logic must be ordinary functions that take a DataFrame and return a DataFrame, held separately from the notebook or pipeline file that calls them. Once that separation exists, testing is unremarkable, and the tests run in seconds on a laptop or a build agent rather than waiting for a cluster.

# src/transforms.py: logic as a plain function, no notebook, no globals
from pyspark.sql import DataFrame, Window, functions as F

def latest_per_loan(df: DataFrame) -> DataFrame:
    w = Window.partitionBy("loan_id").orderBy(F.col("updated_at").desc())
    return df.withColumn("_rn", F.row_number().over(w)).filter("_rn = 1").drop("_rn")

# tests/test_transforms.py: a handful of constructed rows, including the awkward one
def test_latest_per_loan_keeps_newest(spark):
    df = spark.createDataFrame(
        [(1, "2026-10-01", "open"), (1, "2026-10-02", "closed"), (2, None, "open")],
        "loan_id INT, updated_at STRING, status STRING",
    )
    out = {r.loan_id: r.status for r in latest_per_loan(df).collect()}
    assert out == {1: "closed", 2: "open"}

The third row is the point: a null timestamp is the case a hand-tested notebook never meets until production. Ihor Seleznov, a QA engineer at TechFabric, wrote up the same habit for checks that run inside a Databricks notebook in Using PyTest for data quality checks: one function per rule, a business-readable failure message, the bronze checks run again on silver to prove the cleansing worked. We'd run his kind of check against real tables on a schedule and the kind above on every pull request; they catch different bugs.

Promotion between environments #

We'd move a change from development to staging to production as the same artefact with different configuration, never as a separately built thing. The catalog name, source paths, and service principal come from the target's variables, and nothing environment-specific appears in the code.

Our rule for staging is that it holds data representative in shape, including the awkward cases, even when it can't hold real data. A staging environment containing a thousand clean rows validates almost nothing about a pipeline that will meet ten million rows with a null key.

Data changes are deployments too #

A schema change on a published table is an interface change and deserves what interface changes get in software: additive first, a deprecation period for the old shape, and a check for downstream consumers before removal. Unity Catalog lineage makes the consumer question answerable, so we'd wire it into the review as described in Unity Catalog.

The advanced capabilities worth building toward #

Realistic test data without copying it. This is the one we'd build first. A shallow clone of a production Delta table creates a queryable, writable copy that shares the underlying data files, so it costs almost nothing and appears instantly. For Unity Catalog managed tables it needs Databricks Runtime 13.3 LTS or above and lands as a managed table (shallow clone):

CREATE TABLE originations_dev.silver.loans_pr_482 SHALLOW CLONE originations_prd.silver.loans;

One limit to plan around: a table with a table-level row filter or column mask can't be cloned at all. That makes a per-branch test dataset practical where a full copy never was. On the operational side, Lakebase branching does the same thing for Postgres, which means a migration can be tested against real data on every pull request rather than hoped about.

Pipeline expectations as executable contracts. Declarative pipelines let you assert row-level expectations that fail, drop, or quarantine on breach, as in Medallion Architecture. Those assertions run in production continuously, which makes them a test that keeps testing rather than one that passes once in CI.

Environment versions and dependency pinning. Serverless compute exposes an environment version, and pinning it means a platform upgrade does not silently change the behaviour of a running pipeline. In a job it's environment_version in the environments spec. Bundles can build and attach a Python wheel through their artifacts mapping, so shared transformation code is versioned and installed rather than copied between notebooks, which is the most common origin of two pipelines that were supposed to agree and quietly do not.

Policy as code. We'd keep cluster policies, grants and budget policies in the same repository and the same review as everything else. A CI check that fails when a job definition names an all-purpose cluster, or when a table is granted to all users, catches in review what would otherwise be found in an audit.

Models and agents promoted like code. Models registered in Unity Catalog carry aliases and versions across environments, so promotion is an alias change with lineage rather than a copied artefact, which matters most for the agent workloads in Agents.

Blue-green for anything serving traffic. Serving endpoints support splitting traffic across model versions, which turns a model deployment into a gradual shift you can reverse, rather than a switch you throw.

Deploying data platform changes across the clouds

Capability Databricks AWS Azure GCP
Jobs and pipelines as code Declarative Automation Bundles, one file per project CloudFormation or CDK per service ARM or Bicep, plus Data Factory JSON Terraform or Deployment Manager
Per-environment overrides Bundle targets and variables Parameter files per stack Parameter files plus Data Factory global parameters Per-environment Terraform workspaces
Isolated per-developer deployment Development mode prefixes and pauses schedules Build it yourself Build it yourself Build it yourself
Test data without a full copy Shallow clone, plus Lakebase branching Copy the data, or restore a snapshot Copy the data Copy, or BigQuery table clones
Run deployments as a machine identity Service principal, native IAM role plus CodePipeline Service principal plus DevOps Service account plus Cloud Build
Roll a table back Delta time travel and restore Depends on format and backup Depends BigQuery time travel, seven days
One deployment tool for the whole platform Bundles plus Terraform One per service, in practice One per service, in practice One per service, in practice

Rollback #

Delta time travel means a table can be restored to a prior version, which is a real safety net and not a complete one, because restoring one table does not restore the downstream tables computed from the bad data.

We'd work out the rollback path per pipeline in advance, including which tables are affected and in what order they need reprocessing, and write it down where the on-call engineer will find it. The table-level half is one statement, RESTORE TABLE sales_prd.silver.orders TO VERSION AS OF 412, after DESCRIBE HISTORY has told you which version was good; the downstream half is the reprocessing order, which is the part nobody can work out calmly at 3am. That document belongs next to the runbooks described in Observability and Reliability.