databricks-cli/bundle/deploy/terraform/load.go

70 lines
1.4 KiB
Go
Raw Permalink Normal View History

2022-12-15 14:12:47 +00:00
package terraform
import (
"context"
"fmt"
"slices"
2022-12-15 14:12:47 +00:00
"github.com/databricks/cli/bundle"
"github.com/databricks/cli/libs/diag"
"github.com/hashicorp/terraform-exec/tfexec"
2022-12-15 14:12:47 +00:00
)
type loadMode int
const ErrorOnEmptyState loadMode = 0
type load struct {
modes []loadMode
}
2022-12-15 14:12:47 +00:00
func (l *load) Name() string {
return "terraform.Load"
}
func (l *load) Apply(ctx context.Context, b *bundle.Bundle) diag.Diagnostics {
tf := b.Terraform
if tf == nil {
return diag.Errorf("terraform not initialized")
}
err := tf.Init(ctx, tfexec.Upgrade(true))
if err != nil {
return diag.Errorf("terraform init: %v", err)
}
state, err := ParseResourcesState(ctx, b)
2022-12-15 14:12:47 +00:00
if err != nil {
return diag.FromErr(err)
2022-12-15 14:12:47 +00:00
}
err = l.validateState(state)
if err != nil {
return diag.FromErr(err)
}
2022-12-15 14:12:47 +00:00
// Merge state into configuration.
err = TerraformToBundle(state, &b.Config)
if err != nil {
return diag.FromErr(err)
2022-12-15 14:12:47 +00:00
}
return nil
2022-12-15 14:12:47 +00:00
}
func (l *load) validateState(state *resourcesState) error {
if state.Version != SupportedStateVersion {
return fmt.Errorf("unsupported deployment state version: %d. Try re-deploying the bundle", state.Version)
}
if len(state.Resources) == 0 && slices.Contains(l.modes, ErrorOnEmptyState) {
return fmt.Errorf("no deployment state. Did you forget to run 'databricks bundle deploy'?")
}
return nil
}
func Load(modes ...loadMode) bundle.Mutator {
return &load{modes: modes}
2022-12-15 14:12:47 +00:00
}