Skip to content

Commit 6c1fd6c

Browse files
denikIsaac
andcommitted
Skip migration when the plan would recreate a resource
The pre-deploy migration plan-checks the converted state. If that plan would recreate (destroy + create) an existing resource, do not commit the migration: a recreate risks data loss, whether it comes from a conversion that did not faithfully reproduce an immutable field or from a real pending config change (which terraform would recreate too). Fall back to terraform this run and retry the migration next run, once the recreate is applied. Records direct_migrate_recreate_planned. checkPlanOnTempState now returns the plan so the caller can inspect the planned actions. Co-authored-by: Isaac <no-reply@databricks.com>
1 parent 21179e7 commit 6c1fd6c

6 files changed

Lines changed: 134 additions & 9 deletions

File tree

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
bundle:
2+
name: test-bundle
3+
4+
resources:
5+
schemas:
6+
my_schema:
7+
name: myschema
8+
catalog_name: main
9+
storage_root: s3://mybucket/init

‎acceptance/bundle/migrate/auto-migrate-recreate/out.test.toml‎

Lines changed: 3 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.
Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
2+
=== Initial deploy on terraform with storage_root s3://mybucket/init
3+
>>> DATABRICKS_BUNDLE_ENGINE=terraform [CLI] bundle deploy
4+
Uploading bundle files to /Workspace/Users/[USERNAME]/.bundle/test-bundle/default/files...
5+
Created schemas.my_schema
6+
Files: 2 uploaded, 0 deleted
7+
Resources: 1 created, 0 changed, 0 deleted, 0 unchanged
8+
9+
>>> print_migration_telemetry
10+
direct_drymigrate_success true
11+
direct_drymigrate_warnings false
12+
13+
=== Change immutable storage_root in config, then redeploy on direct (auto-migration)
14+
>>> DATABRICKS_BUNDLE_ENGINE=direct [CLI] bundle deploy --auto-approve
15+
Warn: migration to the direct engine would recreate [resources.schemas.my_schema]; deploying on terraform this time
16+
Uploading bundle files to /Workspace/Users/[USERNAME]/.bundle/test-bundle/default/files...
17+
18+
This action will result in the deletion or recreation of the following UC schemas. Any underlying data may be lost:
19+
recreate resources.schemas.my_schema
20+
Recreated schemas.my_schema
21+
Files: 1 uploaded, 0 deleted
22+
Resources: 1 created, 0 changed, 1 deleted, 0 unchanged
23+
24+
>>> print_migration_telemetry
25+
direct_migrate_recreate_planned true
26+
27+
=== Local state was NOT rewritten (still terraform)
28+
>>> find .databricks/bundle -name resources.json -type f
29+
30+
>>> find .databricks/bundle -name terraform.tfstate* -type f
31+
.databricks/bundle/default/terraform/terraform.tfstate.backup
32+
.databricks/bundle/default/terraform/terraform.tfstate
33+
34+
=== Retry on direct: remote now matches config, so the plan is clean and the migration succeeds
35+
>>> DATABRICKS_BUNDLE_ENGINE=direct [CLI] bundle deploy
36+
Migrated 1 resource to direct deployment engine.
37+
Uploading bundle files to /Workspace/Users/[USERNAME]/.bundle/test-bundle/default/files...
38+
Files: 0 uploaded, 0 deleted
39+
Resources: 0 created, 0 changed, 0 deleted, 1 unchanged
40+
41+
>>> print_migration_telemetry
42+
direct_migrated_via_env true
43+
44+
=== Local state is now direct
45+
>>> find .databricks/bundle -name resources.json -type f
46+
.databricks/bundle/default/resources.json
47+
48+
>>> find .databricks/bundle -name terraform.tfstate* -type f
49+
.databricks/bundle/default/terraform/terraform.tfstate.backup
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
export DATABRICKS_BUNDLE_ENGINE=
2+
3+
title "Initial deploy on terraform with storage_root s3://mybucket/init"
4+
trace DATABRICKS_BUNDLE_ENGINE=terraform $CLI bundle deploy
5+
trace print_migration_telemetry
6+
rm -f "$OUT_REQUESTS"
7+
8+
title "Change immutable storage_root in config, then redeploy on direct (auto-migration)"
9+
# storage_root is immutable (recreate_on_changes). The migration's plan check compares the
10+
# new config value against the deployed remote and plans a recreate. Recreating an existing
11+
# resource risks data loss, so the migration is abandoned (direct_migrate_recreate_planned)
12+
# and the bundle stays on terraform. --auto-approve lets the terraform fallback apply the
13+
# recreate the user actually asked for.
14+
update_file.py databricks.yml "storage_root: s3://mybucket/init" "storage_root: s3://mybucket/changed"
15+
trace DATABRICKS_BUNDLE_ENGINE=direct $CLI bundle deploy --auto-approve
16+
trace print_migration_telemetry
17+
rm -f "$OUT_REQUESTS"
18+
19+
title "Local state was NOT rewritten (still terraform)"
20+
trace find .databricks/bundle -name "resources.json" -type f
21+
trace find .databricks/bundle -name "terraform.tfstate*" -type f
22+
23+
title "Retry on direct: remote now matches config, so the plan is clean and the migration succeeds"
24+
trace DATABRICKS_BUNDLE_ENGINE=direct $CLI bundle deploy
25+
trace print_migration_telemetry
26+
rm -f "$OUT_REQUESTS"
27+
28+
title "Local state is now direct"
29+
trace find .databricks/bundle -name "resources.json" -type f
30+
trace find .databricks/bundle -name "terraform.tfstate*" -type f

‎bundle/metrics/metrics.go‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,10 @@ const (
3333
DirectMigrateWarnings = "direct_migrate_warnings"
3434
// True when the post-convert plan check failed; the migration was not committed.
3535
DirectMigratePlanError = "direct_migrate_plan_error"
36+
// True when the post-convert plan check succeeded but the plan would recreate
37+
// (destroy + create) an existing resource; the migration was not committed and
38+
// the run stays on terraform to avoid a destructive plan.
39+
DirectMigrateRecreatePlanned = "direct_migrate_recreate_planned"
3640

3741
// Recorded when an automatic post-deploy migration to the direct engine
3842
// actually ran (state was rewritten). Exactly one of the three keys is true;

‎bundle/statemgmt/direct_migration.go‎

Lines changed: 39 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -8,12 +8,14 @@ import (
88
"io/fs"
99
"os"
1010
"path/filepath"
11+
"slices"
1112

1213
"github.com/databricks/cli/bundle"
1314
"github.com/databricks/cli/bundle/config"
1415
"github.com/databricks/cli/bundle/config/engine"
1516
"github.com/databricks/cli/bundle/config/mutator/resourcemutator"
1617
"github.com/databricks/cli/bundle/deploy"
18+
"github.com/databricks/cli/bundle/deployplan"
1719
"github.com/databricks/cli/bundle/direct"
1820
"github.com/databricks/cli/bundle/direct/dresources"
1921
"github.com/databricks/cli/bundle/direct/dstate"
@@ -100,12 +102,22 @@ func MigrateTerraformState(ctx context.Context, b *bundle.Bundle, requiredEngine
100102
if commit {
101103
// Plan-check the converted state; if it fails, do not commit and fall back to the
102104
// terraform engine (the temp file is cleaned up by the deferred Remove).
103-
if err := checkPlanOnTempState(ctx, b, tempStatePath, cfg); err != nil {
105+
plan, err := checkPlanOnTempState(ctx, b, tempStatePath, cfg)
106+
if err != nil {
104107
b.Metrics.SetBoolValue(metrics.DirectMigratePlanError, true)
105108
log.Warnf(ctx, "migration to the direct engine failed its plan check; deploying on terraform this time: %v", err)
106109
return false, nil
107110
}
108111

112+
// Do not migrate into a plan that would recreate an existing resource: a recreate
113+
// is a destroy + create and risks data loss. Fall back to terraform this run (the
114+
// migration retries next run, once any pending recreate has been applied).
115+
if recreated := recreatedResources(plan); len(recreated) > 0 {
116+
b.Metrics.SetBoolValue(metrics.DirectMigrateRecreatePlanned, true)
117+
log.Warnf(ctx, "migration to the direct engine would recreate %v; deploying on terraform this time", recreated)
118+
return false, nil
119+
}
120+
109121
// Commit to the workspace by pushing resources.json (serial tf+1). This upload is
110122
// the hard commit: once it lands it outranks any leftover terraform state by serial,
111123
// so engine selection can no longer pick terraform and the cleanup in
@@ -201,11 +213,13 @@ func DryRunMigrationTelemetry(ctx context.Context, b *bundle.Bundle) {
201213
}
202214

203215
// checkPlanOnTempState opens the migrated state at tempStatePath in read mode,
204-
// runs a full plan against it, and returns a non-nil error if the plan fails.
205-
// Individual planning errors are emitted as warnings with warnPrefix so they
206-
// are visible without failing the deploy. The plan is run in an isolated
207-
// context so its diagnostics do not affect the deploy's own error state.
208-
func checkPlanOnTempState(ctx context.Context, b *bundle.Bundle, tempStatePath string, cfg *config.Root) error {
216+
// runs a full plan against it, and returns the plan (and a non-nil error if the
217+
// plan fails). Individual planning errors are emitted as warnings with warnPrefix
218+
// so they are visible without failing the deploy. The plan is run in an isolated
219+
// context so its diagnostics do not affect the deploy's own error state. The
220+
// returned plan lets the caller inspect the planned actions (e.g. reject a
221+
// migration that would recreate a resource).
222+
func checkPlanOnTempState(ctx context.Context, b *bundle.Bundle, tempStatePath string, cfg *config.Root) (*deployplan.Plan, error) {
209223
planCtx := logdiag.IsolatedContext(ctx)
210224
logdiag.SetCollect(planCtx, true)
211225
defer func() {
@@ -223,11 +237,27 @@ func checkPlanOnTempState(ctx context.Context, b *bundle.Bundle, tempStatePath s
223237
// This plan is not created with the deployment history feature enabled,
224238
// so we can safely pass false for withDeploymentHistory.
225239
if err := planBundle.StateDB.Open(planCtx, tempStatePath, false, false, dstate.WithDeploymentHistory(false), dstate.OpenDmsArgs{}); err != nil {
226-
return fmt.Errorf("opening migrated state for plan check: %w", err)
240+
return nil, fmt.Errorf("opening migrated state for plan check: %w", err)
227241
}
228242

229-
_, err := planBundle.CalculatePlan(planCtx, b.WorkspaceClient(ctx), cfg)
230-
return err
243+
return planBundle.CalculatePlan(planCtx, b.WorkspaceClient(ctx), cfg)
244+
}
245+
246+
// recreatedResources returns the sorted keys of resources the plan would recreate
247+
// (destroy + create). A migration should not commit into such a plan: a recreate
248+
// on a resource that already exists risks destroying it, whether it comes from a
249+
// conversion that did not faithfully reproduce an immutable field or from a real
250+
// pending config change (which terraform would recreate too). In both cases the
251+
// safe choice is to stay on terraform this run and retry the migration later.
252+
func recreatedResources(plan *deployplan.Plan) []string {
253+
var keys []string
254+
for key, entry := range plan.Plan {
255+
if entry.Action == deployplan.Recreate {
256+
keys = append(keys, key)
257+
}
258+
}
259+
slices.Sort(keys)
260+
return keys
231261
}
232262

233263
// BackupTerraformState moves the terraform state to .backup both remotely

0 commit comments

Comments
 (0)