Managing Databricks environments can quickly become overwhelming as jobs, AI Search indexes, and pipeline artifacts accumulate, making manual cleanup, logging, and compliance difficult. This article introduces a practical automation strategy that uses Declarative Automation Bundles to simplify environment hygiene. The solution identifies and proposes cleanup candidates - it does not delete anything automatically. A scheduled discovery job records every candidate and never deletes; deletion is a separate, manually started job protected by protected-resource exclusions, an explicit approval gate, a per-run cap, and recovery controls, so nothing is removed without review. Every action is recorded in a Delta audit table and surfaced in a dashboard for transparency. Learn how to reclaim control of your workspace, reduce clutter, and gain transparency, all with scalable, repeatable best practices for modern data platforms.
Before deploying the cleanup bundle, make sure the following are in place:
As Databricks workspaces grow, they tend to accumulate jobs, AI Search indexes, dashboards, and other artifacts that are no longer needed. Over time, these unused assets clutter the workspace, consume compute and storage resources, and make governance harder to maintain. Cleaning them up manually, especially across multiple environments, is tedious and error-prone.
The goal of this project is to automate that cleanup safely and transparently: candidates are found automatically, but nothing is deleted without a recorded approval. The safeguards are listed once, in "Safety, Approval, and Execution Model" below.
Every action is logged in a Delta table and visualized in an AI/BI dashboard, making cleanup governed, auditable, and repeatable.
Scope: single-workspace by design, serverless compute
The two layers operate at different scopes, and the workflow reconciles them deliberately. System tables are account-level, so the discovery side sees resources across every workspace in the account. The SDK cleanup (jobs, dashboards, AI Search indexes), however, is per-workspace - it can only act on the workspace the bundle is deployed to. This solution is single-workspace by design: every system-table query is filtered to the current workspace_id, so the SDK layer never tries to act on a resource it cannot see. To cover multiple workspaces, deploy the bundle to each one rather than fanning out from a single deployment.
The workflow itself runs on serverless compute. Both jobs are lightweight - a handful of system-table queries plus SDK calls - so serverless jobs and serverless SQL are the natural fit, and they avoid the irony of a cleanup tool spinning up a classic cluster just to tidy up.
Each cleanup task is defined as a notebook within a Declarative Automation Bundle, deployed per environment with configuration overrides. Declarative Automation Bundles natively support parameterization, allowing cleanup logic to adapt per environment without changing the code.
# Per-environment cleanup toggles. Whether a run deletes is decided by the JOB,
# not this file: cleanup_discover never deletes; cleanup_execute verifies and
# deletes approved candidates.
# allow_execute -> true lets cleanup_execute delete in this environment
# (false = cleanup_execute exits without touching anything)
# *_cleanup -> enable/disable each cleanup type (false = notebook exits)
# audit_table -> where every action is logged; point the Lakeview dashboard
# at this same three-level (catalog.schema.table) name.
# Applied to every environment unless that environment overrides the key. Keeps
# allow_execute: false as the safe baseline - an env must opt in to deletion.
defaults:
allow_execute: false
# Hard cap on live deletions per run, per resource type (jobs, dashboards, AI Search
# indexes - each is deleted by exactly one task) - limits blast radius if a rule
# is misconfigured. cleanup_discover flags all candidates regardless.
max_deletions_per_run: 25
# Approval gate: when true, cleanup_execute only deletes resources
# that have a recorded approval in <audit catalog.schema>.cleanup_approvals.
# Reviewing the dashboard is not authorization - reviewers must INSERT an approval
# row. cleanup_discover always flags every candidate regardless of this setting.
require_approval: true
# Protected resources are never deleted, regardless of thresholds (shared by all
# environments). Tags match a job's tag keys or values; exclude_ids are explicit
# "<type>:<id>" (or bare id) entries, e.g. ["job:123", "dashboard:abc"].
protected:
exclude_pipeline_jobs: true
tags:
- retain
- production-critical
exclude_ids: []
dev:
job_cleanup: true
dashboard_cleanup: true
ai_search_index_cleanup: true
# no allow_execute here -> inherits false: dev can discover but never delete
audit_table: maintenance.cleanup.cleanup_log
stage:
job_cleanup: true
dashboard_cleanup: true
ai_search_index_cleanup: true
allow_execute: true
audit_table: maintenance.cleanup.cleanup_log
prod:
job_cleanup: true
dashboard_cleanup: true
ai_search_index_cleanup: true
allow_execute: true
audit_table: maintenance.cleanup.cleanup_log
Thresholds live in a separate thresholds.yaml file: jobs are inactive after 90 days and dashboards are stale after 60 days, while clusters, warehouses, and serving endpoints are flagged for review by cost and activity rather than deleted. Discovery and deletion run as two separate jobs - see "Safety, Approval, and Execution Model".
Each cleanup type has its own toggle (job_cleanup, dashboard_cleanup, ai_search_index_cleanup), so you can enable them one at a time.
The Databricks SDK is the only layer that deletes. Before acting, it checks what system tables cannot: whether a job run is in progress right now, protection tags and pipeline tasks, and whether an AI Search index's source table still exists. For how long a job has been idle, it uses the system-table last run (job_activity), because the Jobs API keeps only about 60 days of run history. If that system-table history is shorter than job_activity_window_days (for example, system tables were enabled recently), a job with no recent runs is left for manual review instead of being assumed idle - and a job with no runs at all counts as never run only if that history goes back to when the job was created - and a never-run job is skipped unless delete_never_run is true, however old it is. Each resource type has exactly one deleting task, and it deletes only approved candidates.
Job Cleanup - a simplified excerpt of notebooks/01_job_cleanup.py. It lists all jobs, skips protected ones, works out how long each job has been idle, and flags those beyond the threshold. Only cleanup_execute deletes, and only approved jobs:
from databricks.sdk import WorkspaceClient
from datetime import datetime, timezone
w = WorkspaceClient() # auth via env/DAB; no manual host or headers
now = datetime.now(timezone.utc)
deleted = 0
for job in w.jobs.list(expand_tasks=True): # tasks are needed to spot pipeline jobs
if is_protected(job): # SDP/Lakeflow jobs, protected tags, exclude_ids
logger.log(resource_type="job", resource_id=job.job_id,
action="SKIPPED", reason="protected")
continue
# The Jobs API keeps only ~60 days of runs: use it to spot a run in progress,
# and fall back to the system-table last run (job_activity) for idle time.
run = next(iter(w.jobs.list_runs(job_id=job.job_id, limit=1)), None)
if run and run.state.life_cycle_state not in TERMINAL_STATES:
continue # running right now - never a candidate
if next(iter(w.jobs.list_runs(job_id=job.job_id, active_only=True, limit=1)), None):
continue # an older run is still going (newest may be SKIPPED)
last_run_ms = (run.end_time or run.start_time) if run else job_activity.get(str(job.job_id))
if last_run_ms is None: # no run anywhere (see delete_never_run)
logger.log(resource_type="job", resource_id=job.job_id,
action="SKIPPED", reason="never run - manual review")
continue
days_idle = (now - datetime.fromtimestamp(last_run_ms / 1000, tz=timezone.utc)).days
if days_idle <= cfg.job_inactive_days: # default 90
continue # still active, not a candidate
block = gate.block_reason("job", job.job_id, deleted) # approval + per-run cap
if block:
logger.log(resource_type="job", resource_id=job.job_id,
action="SKIPPED", reason=f"Candidate - {block}")
continue
if dry_run: # cleanup_discover
logger.log(resource_type="job", resource_id=job.job_id,
action="FLAGGED", reason=f"Inactive {days_idle} days")
else: # cleanup_execute
w.jobs.delete(job_id=job.job_id) # permanent: no trash / no undelete API
logger.log(resource_type="job", resource_id=job.job_id,
action="DELETED", reason=f"Inactive {days_idle} days",
details=gate.approval("job", job.job_id)) # who approved it, when
deleted += 1
Dashboard Cleanup - Uses the dashboards SDK (w.lakeview.list()) to find AI/BI dashboards that nobody has edited, viewed, or queried for longer than dashboard_inactive_days (default 60). Edits come from update_time; views and query runs come from system.access.audit, so a dashboard people still open is never a candidate. If the audit log holds fewer days than dashboard_inactive_days (for example, it was enabled recently), a dashboard that looks stale is left for manual review instead. Stale dashboards are moved to Trash with w.lakeview.trash(dashboard_id=...) - a soft delete that stays recoverable for 30 days. The workflow does not purge already-trashed dashboards, so the Trash recovery window is always preserved.
AI Search Cleanup - Lists AI Search indexes (w.vector_search_indexes.list_indexes(...)) and flags those whose source Delta table no longer exists in Unity Catalog (checked with w.tables.exists(...)). Because index deletion is permanent, with no trash or restore API, the safeguard here is the orphaned-source check itself: the source is already gone, so there is nothing left to re-sync - and deletion still runs only after discovery and a recorded approval, in the execute job.
This is the discovery layer for cost. System tables are read-only, so they find candidates but never delete them. Instead of relying on SDK metadata alone, we query Databricks system tables to identify resources that are incurring cost but delivering no value. System tables provide billing, compute, and job-execution history that resource metadata alone does not expose - including the actual dollars spent per resource once DBU usage is priced with system.billing.list_prices.
The sample queries in this section use a :workspace_id parameter, because system tables hold data for every workspace in the account. When the SQL editor asks for it, enter your workspace ID - the number after adb- in an Azure workspace URL, or the ?o= value in the browser address bar. The notebooks fill it in automatically.
Find jobs that haven't run in 90 days, and jobs that cost a lot for few runs, by joining system.billing.usage and system.billing.list_prices (for cost) with system.lakeflow.job_run_timeline (for activity):
WITH job_activity AS ( -- last run + failures in the analysis window
SELECT
job_id,
MAX(COALESCE(period_end_time, period_start_time)) AS last_run,
COUNT(DISTINCT run_id) AS total_runs, -- runs, not time slices
COUNT(DISTINCT CASE WHEN result_state NOT IN ('SUCCESS', 'SUCCEEDED')
THEN run_id END) AS failed_runs -- result_state is on the final slice
FROM system.lakeflow.job_run_timeline
WHERE workspace_id = :workspace_id
AND period_start_time >= current_date() - INTERVAL 180 DAYS -- job_activity_window_days
GROUP BY job_id
),
job_costs AS ( -- list-price $ per job over 90 days
SELECT
u.usage_metadata.job_id AS job_id,
SUM(u.usage_quantity * lp.pricing.default) AS cost_90d
FROM system.billing.usage u
JOIN system.billing.list_prices lp
ON u.cloud = lp.cloud
AND u.sku_name = lp.sku_name
AND u.usage_start_time >= lp.price_start_time
AND (lp.price_end_time IS NULL OR u.usage_start_time < lp.price_end_time)
WHERE u.usage_metadata.job_id IS NOT NULL
AND u.workspace_id = :workspace_id
AND u.usage_date >= current_date() - INTERVAL 90 DAYS
GROUP BY u.usage_metadata.job_id
),
latest_jobs AS ( -- jobs that still exist (system.lakeflow.jobs is SCD2)
SELECT job_id, name, delete_time
FROM system.lakeflow.jobs
WHERE workspace_id = :workspace_id
QUALIFY ROW_NUMBER() OVER (PARTITION BY job_id ORDER BY change_time DESC) = 1
)
SELECT
a.job_id,
j.name AS job_name,
DATEDIFF(DAY, a.last_run, current_timestamp()) AS days_idle,
a.total_runs,
a.failed_runs,
COALESCE(c.cost_90d, 0) AS cost_90d,
CASE
WHEN DATEDIFF(DAY, a.last_run, current_timestamp()) > 90 THEN 'CANDIDATE_DELETE'
WHEN a.failed_runs > a.total_runs * 0.8 THEN 'CANDIDATE_REVIEW'
WHEN COALESCE(c.cost_90d, 0) > 1000 AND a.total_runs < 5 THEN 'CANDIDATE_REVIEW'
ELSE 'HEALTHY'
END AS recommendation
FROM job_activity a
JOIN latest_jobs j ON a.job_id = j.job_id
LEFT JOIN job_costs c ON a.job_id = c.job_id
WHERE j.delete_time IS NULL -- skip deleted jobs and one-off runs
ORDER BY cost_90d DESC;
This surfaces jobs idle for 90+ days, jobs where over 80% of runs fail (wasted compute), and high-cost jobs with little activity - ranked by the dollars they consumed over the last 90 days. It only sees runs inside the analysis window (job_activity_window_days), so jobs with no run in that window are handled by the job cleanup task, not by this query.
Find idle clusters burning money, by joining system.compute.clusters with the same priced billing data. Only all-purpose clusters are reviewed: job and pipeline (SDP) clusters exist for a single run and terminate with it, and their cost is billed to the job or pipeline:
WITH cluster_costs AS ( -- list-price $ and active days over 30 days
SELECT
u.usage_metadata.cluster_id AS cluster_id,
SUM(u.usage_quantity * lp.pricing.default) AS cost_30d,
COUNT(DISTINCT u.usage_date) AS active_days
FROM system.billing.usage u
JOIN system.billing.list_prices lp
ON u.cloud = lp.cloud
AND u.sku_name = lp.sku_name
AND u.usage_start_time >= lp.price_start_time
AND (lp.price_end_time IS NULL OR u.usage_start_time < lp.price_end_time)
WHERE u.usage_metadata.cluster_id IS NOT NULL
AND u.workspace_id = :workspace_id
AND u.usage_date >= current_date() - INTERVAL 30 DAYS
GROUP BY u.usage_metadata.cluster_id
),
latest_clusters AS ( -- current all-purpose clusters (clusters is SCD2)
SELECT cluster_id, cluster_name, owned_by FROM ( -- latest row per cluster FIRST
SELECT cluster_id, cluster_name, owned_by, cluster_source, delete_time
FROM system.compute.clusters
WHERE workspace_id = :workspace_id
QUALIFY ROW_NUMBER() OVER (PARTITION BY cluster_id ORDER BY change_time DESC) = 1
) WHERE delete_time IS NULL -- then drop deleted clusters
AND cluster_source NOT IN ('JOB', 'PIPELINE', 'PIPELINE_MAINTENANCE') -- one-run clusters
)
SELECT
cl.cluster_id,
cl.cluster_name,
cl.owned_by,
COALESCE(cc.cost_30d, 0) AS cost_30d,
COALESCE(cc.active_days, 0) AS active_days,
CASE
WHEN COALESCE(cc.active_days, 0) = 0 THEN 'CANDIDATE_DELETE'
WHEN cc.cost_30d > 5000 AND cc.active_days < 5 THEN 'CANDIDATE_REVIEW'
ELSE 'HEALTHY'
END AS recommendation
FROM latest_clusters cl
LEFT JOIN cluster_costs cc ON cl.cluster_id = cc.cluster_id
ORDER BY cost_30d DESC;
The same billing-versus-activity pattern extends to other compute. For SQL warehouses, join system.billing.usage against system.query.history to find warehouses that cost money but receive no queries. For model serving endpoints, join system.billing.usage against system.serving.endpoint_usage to find endpoints that cost money but receive no traffic. In every case the shape is the same: price the usage, measure the activity, and flag the resources where cost is high and activity is zero. Every one of these queries also filters on the current workspace_id, so the analysis only flags resources in the workspace the bundle runs in - matching the single-workspace scope described earlier. The notebook fills this in automatically from its execution context; to run these queries ad hoc in the SQL editor, provide your workspace id for the :workspace_id parameter.
Discovery and deletion are deliberately separate jobs - cleanup_discover, then cleanup_execute - so that finding a candidate and removing it are never the same action.
Before any resource is deleted, the workflow enforces a fixed set of safeguards:
Deletion type and recovery differ by resource type:
|
Resource |
Deletion type |
Recovery path |
Retention window |
Key limitation |
|
Jobs |
Permanent (jobs/delete), no trash |
Redeploy the job definition from DAB/Git |
None |
Run history is lost; no restore/undelete API |
|
AI/BI dashboards |
Soft delete to workspace Trash (use w.lakeview.trash) |
Workspace > Trash > Restore, or list with show_trashed=true and restore via SDK |
30 days, then permanently purged |
Some workspace delete paths bypass Trash and are unrecoverable; always use the trash endpoint, not a hard delete |
|
AI Search Indexes |
Permanent, no trash |
Recreate the index and re-sync from its source Delta table |
None |
No restore API; only works if the source Delta table still exists |
Clusters, SQL warehouses, and model serving endpoints are surfaced as cost candidates by the system-table analysis but are not deleted by this workflow - they are flagged for human review only. For reference, terminated clusters retain their config for 30 days (indefinitely if pinned).
Note that Git/DAB rollback restores deployment code and configuration. It does not restore a resource or its data once that resource has been deleted through an API call. Capturing each candidate's exportable configuration as JSON before deletion, as a best-effort recovery aid rather than a guaranteed restore, is planned as a future enhancement; see Recovery Snapshots under Future Work.
Every action - flagged, skipped, or deleted - is logged to a single Delta table (maintenance.cleanup.cleanup_log) using a shared CleanupLogger class:
class CleanupLogger:
def __init__(self, spark, table="maintenance.cleanup.cleanup_log"):
# creates the schema + table if missing (not the catalog)
self.spark = spark
self.table = table
self.entries = []
catalog, schema, _ = table.split(".")
self._ensure_table(catalog, schema)
def log(self, environment, resource_type, resource_id, resource_name,
owner, action, reason, dry_run=False, details=None):
# buffers a structured entry; flush() writes the batch
self.entries.append({
"timestamp": datetime.now(timezone.utc),
"environment": environment,
"resource_type": resource_type,
"resource_id": str(resource_id),
"resource_name": resource_name,
"owner": owner or "unknown",
"action": action,
"reason": reason,
"dry_run": dry_run,
"details": json.dumps(details) if details else None,
})
The log table captures: timestamp, environment, resource type, resource ID, resource name, owner, action (FLAGGED / SKIPPED / DELETED), reason, and a JSON details column for cost and metadata - for a deletion, including who approved it and when (approved_by, approved_at). A failed API call is logged SKIPPED with the error as the reason. Approvals live in a separate cleanup_approvals table, and each job's system-table last run and cost in job_activity.
Note: cleanup_log is an audit log (what happened to a resource), not a recovery snapshot. Persisting each resource's full configuration for reconstruction is planned as a future enhancement (see Future Work).
All logs feed into an AI/BI dashboard where workspace admins can visualize cleanup activity at a glance. The SQL examples below (and the deployed dashboard datasets) use the default table maintenance.cleanup.cleanup_log; replace it with the audit_table you configured in config.yaml:
Cleanup summary - how many resources were deleted, skipped, and flagged, by resource type (each resource counted once):
SELECT
resource_type,
action,
COUNT(DISTINCT resource_id) AS count
FROM maintenance.cleanup.cleanup_log
WHERE timestamp >= DATEADD(DAY, -30, CURRENT_DATE())
GROUP BY resource_type, action
Top wasted resources - flagged by the latest system-table scan, sorted by cost:
SELECT
environment,
resource_type,
resource_name,
resource_id,
reason,
get_json_object(details, '$.cost') AS estimated_cost,
owner,
timestamp
FROM maintenance.cleanup.cleanup_log f
WHERE
action = 'FLAGGED'
AND reason LIKE 'CANDIDATE\\_%' -- flagged by the system-table scan
AND timestamp >= DATEADD(DAY, -7, CURRENT_DATE())
AND CAST(get_json_object(details, '$.cost') AS DOUBLE) > 0 -- only items that cost money
AND NOT EXISTS (
-- not deleted since
SELECT 1
FROM maintenance.cleanup.cleanup_log d
WHERE
d.action = 'DELETED'
AND d.environment = f.environment
AND d.resource_type = f.resource_type
AND d.resource_id = f.resource_id
AND d.timestamp >= f.timestamp
)
QUALIFY
timestamp >= MAX(timestamp) OVER (PARTITION BY environment) - INTERVAL 15 MINUTES -- latest scan only
AND ROW_NUMBER() OVER (
PARTITION BY environment, resource_type, resource_id
ORDER BY timestamp DESC
) = 1 -- once per resource
ORDER BY
CAST(get_json_object(details, '$.cost') AS DOUBLE) DESC
LIMIT 20
The deployed dashboard follows the same three phases. At the top, an environment filter (dev, stage, prod) applies to every panel, and a row of three counters shows what is waiting for approval (jobs, dashboards, and AI Search indexes - the types the workflow can delete), what is approved but not yet run, and what was deleted in the last 30 days. Section 1, Discover, puts three panels side by side: candidates by resource type, what the cleanup did in the last 7 days (flagged, skipped, deleted), and a table of every candidate with its reason, owner, and resource ID - the ID a reviewer copies into the approval. Review-only items (clusters, SQL warehouses, serving endpoints, and cost or failure signals for jobs) are listed in that table but not counted as waiting for approval. Section 2, Approve, lists approvals still waiting for cleanup_execute and when each one expires. Section 3, Execute, lists the deletions of the last 30 days and who approved each one. Each resource appears once, in its state from the latest discovery run: re-running discovery does not inflate the numbers, and items found active again or deleted since they were flagged drop out of the candidate panels.
How the Two Layers Work Together
|
|
Databricks SDK |
System Table-Driven |
|
Best for |
Removing specific resources |
Finding cost waste |
|
Cost visibility |
No |
Yes, estimated $ per resource (list price) |
|
Discovery |
Limited to API metadata |
Rich, billing × activity |
|
Recommendation |
Execute deletions |
Identify candidates |
Use both together. The workflow runs the system-table analysis first to find cost waste and attach cost to each candidate. The SDK tasks then verify each resource's current state and delete only approved candidates, up to the cap - one deleting task per resource type.
Using Declarative Automation Bundles replaces ad hoc cleanup scripts with a standardized, version-controlled, and portable deployment framework. Each environment, dev, stage, and prod, shares the same cleanup codebase but applies its own configuration. DAB automates promotion, ensures consistency across environments, and provides rollback support via Git versioning.
Deleting a resource through an API call does not remove its Terraform or DAB declaration. If the resource is defined as code, the next terraform apply or databricks bundle deploy will simply recreate it, and the cleanup will appear to "not stick." Reconciling code-managed resources is a recommended operating practice rather than something this workflow automates today. Before acting on any candidate, identify the resource's source of truth and take one of three explicit paths:
In practice this means a reviewer either opens a code change or approves the API deletion, but a code-managed resource is never silently deleted. This keeps the workspace and its infrastructure definitions in agreement. Automating this source-of-truth detection is a possible future enhancement.
Orphaned bundle resources (monorepos)
In a monorepo, a platform team's pipeline deploys every project bundle it finds. When a project team deletes its bundle folder, nobody runs bundle destroy - it needs the bundle config that was just deleted - so the bundle's jobs, pipelines, and dashboards stay in the workspace, still scheduled and still billed, with their state left under .bundle/. Unlike the case above, no future deploy will recreate them, so API deletion is the right fix.
Cleanup runs as two jobs on the same target: cleanup_discover finds candidates and never deletes, and cleanup_execute deletes only approved candidates after a person records approvals. Run every step against the same target - candidates, approvals, and deletions all belong to one workspace and environment. The examples use prod. The dev target is for trying the bundle safely: it discovers everything but has allow_execute: false, so cleanup_execute exits there without deleting. If you deployed an earlier, single-job version of this bundle, the next deploy deletes the old cleanup_workflow job and replaces it with the two new jobs.
Set your workspace (one-time). In databricks.yml, replace the placeholder workspace.host (https://<your-workspace>.azuredatabricks.net) with your workspace URL, or set a host per target.
Set your audit catalog (one-time, before the first run). The audit_table in config.yaml defaults to maintenance.cleanup.cleanup_log. Change the catalog (the first part of that name) in each environment block of config.yaml to a catalog you already own, and update the same table name in the dashboard datasets (dashboards/cleanup_audit.lvdash.json) so they match. The bundle creates the schema and table, but not the catalog.
export BUNDLE_VAR_warehouse_id=<sql_warehouse_id> # every deploy AND run needs it
databricks bundle deploy --target prod
databricks bundle run cleanup_discover --target prod # finds candidates, deletes nothing
Every candidate is written to cleanup_log with action FLAGGED. No resource is touched.
No job records approvals; this is the human decision between discovery and deletion. Review the flagged candidates in the AI/BI dashboard, then record an approval for each one you want removed by running an INSERT in the SQL editor or a notebook. The easiest way is to copy the item straight from the audit log, so you never type a resource ID by hand:
INSERT INTO maintenance.cleanup.cleanup_approvals
(run_id, environment, resource_type, resource_id, approved_by, approved_at)
SELECT DISTINCT '<discover_run_id>', environment, resource_type, resource_id,
current_user(), current_timestamp()
FROM maintenance.cleanup.cleanup_log
WHERE action = 'FLAGGED' AND environment = 'prod'
AND resource_type IN ('job', 'dashboard', 'ai_search_index')
AND timestamp >= current_timestamp() - INTERVAL 7 DAYS
AND resource_name = '<name shown in the dashboard>';
databricks bundle run cleanup_execute --target prod # verify + delete approved items
cleanup_execute deletes only resources that carry a matching approval for that environment, up to max_deletions_per_run. Anything without an approval is logged SKIPPED (no approval recorded). Each deletion writes DELETED to the audit log; if an API call fails, the item is logged SKIPPED with the error.
SELECT resource_type, resource_name, action, reason,
get_json_object(details, '$.approved_by') AS approved_by
FROM maintenance.cleanup.cleanup_log
WHERE environment = 'prod' AND dry_run = false
AND timestamp >= current_timestamp() - INTERVAL 1 DAY
ORDER BY timestamp DESC;
This closes the loop: every deletion is backed by a FLAGGED row, a recorded approval, and a DELETED row in the audit log that names the approver - all visible in the dashboard's Approvals section. Reviewing the dashboard alone never deletes anything.
The repository includes a Genie Code skill, skills/workspace-cleanup/SKILL.md. Copy the folder into /Users/<you>/.assistant/skills/ (or /Workspace/.assistant/skills/ for everyone), and reviewers can ask in plain language: "what did discovery flag in prod?", "why wasn't this job deleted?", or "draft approvals for these two dashboards". The skill reads cleanup_log, cleanup_approvals, and job_activity, and drafts the step 2 SQL for a person to check and run. It never inserts an approval, never runs cleanup_execute, and never calls a delete API. Genie runs as the user, so only approvers can run the INSERT it drafts.
Full source code, notebooks, DAB configuration, and dashboard queries are available on GitHub: https://github.com/databricks-solutions/databricks-blogposts/tree/main/2026-07-databricks-workspace-...
The cleanup_log table is an audit log: it records what happened to a resource (who, when, which action, and why). It is deliberately not a recovery snapshot, and the two should not be conflated. A row saying a job was DELETED does not let you rebuild that job.
A future iteration should persist each resource's exportable configuration as JSON before deletion, so a flagged-then-deleted resource can be reconstructed or reviewed after the fact. Two placement options: a dedicated resource_config_json column on the log/snapshot row, or a related cleanup_snapshots table keyed by run_id + resource_id (preferred, so audit rows stay lean and snapshots can carry their own retention and access controls).
Fields to capture per snapshot:
|
Field |
Purpose |
|
resource_type |
job / dashboard / vector index / cluster / warehouse |
|
workspace_id / account_id |
where the resource lived |
|
resource_id |
the deleted resource's identifier |
|
owner |
resource owner at snapshot time |
|
dependencies |
upstream/downstream references (lineage, source tables, linked jobs) |
|
source_of_truth |
Terraform / DAB / ad-hoc (ties into the IaC reconciliation section) |
|
config_schema_version |
version of the export schema, so future restores can migrate old snapshots |
|
snapshot_timestamp |
when the config was captured (immediately pre-deletion) |
|
checksum |
hash of the config JSON to detect tampering or corruption |
|
resource_config_json |
the full exportable configuration payload |
Governance the snapshot must document:
Important caveat to state plainly: a configuration snapshot is a best-effort recovery aid, not a guaranteed restore. It may not be sufficient to recreate every resource or its dependent data. A permanently deleted job can be recreated from its JSON, but its run history is gone; a deleted vector index can be redeclared, but its embeddings must be rebuilt from source; dashboards restored from config lose in-place edits made outside DAB. Snapshots restore declarations and configuration, not state or derived data.
Related audit-schema additions (same effort): extend the log with run_id, job_run_id, initiated_by, approved_by, approval_timestamp, deployment_version, policy_result, api_response, failure_reason, and recovery_status, and add explicit APPROVED and FAILED actions alongside FLAGGED, SKIPPED, and DELETED. Together these turn the log from "what happened" into a full record of who authorized it, what the system did, and whether it can be recovered.
In a monorepo, a bundle's jobs, pipelines, and dashboards stay in the workspace when its folder is deleted without bundle destroy (see "Orphaned bundle resources" above). The cleanup does not detect these today: a leftover job that is still scheduled keeps running, so it never looks idle. A future version could flag them directly. A bundle-deployed job records its bundle in job.settings.deployment, so discovery could flag jobs whose bundle is no longer in the repo's list of active bundles, and send them through the same approval and execution steps. This needs a reliable source for that list, such as a file the platform pipeline maintains. Until then, the prevention step in the platform pipeline is what stops orphaned resources.
The next step is to layer conversational and agentic assistance on top of the same governed foundation. The Genie Code skill in step 5 of Getting Started is a first step: it explains why a resource was flagged and drafts approvals, without granting anyone delete access. A Genie space over the same tables could extend this to reviewers who don't work in notebooks or the SQL editor. Agents could help generate dry-run plans, check recovery and dependency signals before a resource is proposed, route candidates through the approval step, and verify outcomes after execution. In every case the deletion itself stays behind the same guardrails described above - deterministic policy checks, scoped credentials, an explicit approval gate, and complete audit logging - so added intelligence improves the review experience without widening what can actually be deleted.
By combining DAB, system tables, structured logging, and visual dashboards, this solution turns a tedious maintenance chore into an automated, insight-driven workflow for modern Databricks operations. Your workspace stays clean, your costs stay visible, and every action is auditable.
You must be a registered user to add a comment. If you've already registered, sign in. Otherwise, register and sign in.