2022-12-15 14:12:47 +00:00
|
|
|
package terraform
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
2023-03-30 10:01:09 +00:00
|
|
|
"fmt"
|
2023-11-02 11:00:30 +00:00
|
|
|
"slices"
|
2022-12-15 14:12:47 +00:00
|
|
|
|
2023-05-16 16:35:39 +00:00
|
|
|
"github.com/databricks/cli/bundle"
|
2023-03-30 10:01:09 +00:00
|
|
|
"github.com/hashicorp/terraform-exec/tfexec"
|
2023-05-10 09:02:25 +00:00
|
|
|
tfjson "github.com/hashicorp/terraform-json"
|
2022-12-15 14:12:47 +00:00
|
|
|
)
|
|
|
|
|
2023-11-02 11:00:30 +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"
|
|
|
|
}
|
|
|
|
|
2023-05-24 12:45:19 +00:00
|
|
|
func (l *load) Apply(ctx context.Context, b *bundle.Bundle) error {
|
2023-03-30 10:01:09 +00:00
|
|
|
tf := b.Terraform
|
|
|
|
if tf == nil {
|
2023-05-24 12:45:19 +00:00
|
|
|
return fmt.Errorf("terraform not initialized")
|
2023-03-30 10:01:09 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
err := tf.Init(ctx, tfexec.Upgrade(true))
|
|
|
|
if err != nil {
|
2023-05-24 12:45:19 +00:00
|
|
|
return fmt.Errorf("terraform init: %w", err)
|
2023-03-30 10:01:09 +00:00
|
|
|
}
|
|
|
|
|
2022-12-15 14:12:47 +00:00
|
|
|
state, err := b.Terraform.Show(ctx)
|
|
|
|
if err != nil {
|
2023-05-24 12:45:19 +00:00
|
|
|
return err
|
2022-12-15 14:12:47 +00:00
|
|
|
}
|
|
|
|
|
2023-11-02 11:00:30 +00:00
|
|
|
err = l.validateState(state)
|
2023-05-10 09:02:25 +00:00
|
|
|
if err != nil {
|
2023-05-24 12:45:19 +00:00
|
|
|
return err
|
2023-05-10 09:02:25 +00:00
|
|
|
}
|
|
|
|
|
2022-12-15 14:12:47 +00:00
|
|
|
// Merge state into configuration.
|
|
|
|
err = TerraformToBundle(state, &b.Config)
|
|
|
|
if err != nil {
|
2023-05-24 12:45:19 +00:00
|
|
|
return err
|
2022-12-15 14:12:47 +00:00
|
|
|
}
|
|
|
|
|
2023-05-24 12:45:19 +00:00
|
|
|
return nil
|
2022-12-15 14:12:47 +00:00
|
|
|
}
|
|
|
|
|
2023-11-02 11:00:30 +00:00
|
|
|
func (l *load) validateState(state *tfjson.State) error {
|
2023-05-10 09:02:25 +00:00
|
|
|
if state.Values == nil {
|
2023-11-02 11:00:30 +00:00
|
|
|
if slices.Contains(l.modes, ErrorOnEmptyState) {
|
|
|
|
return fmt.Errorf("no deployment state. Did you forget to run 'databricks bundle deploy'?")
|
|
|
|
}
|
|
|
|
return nil
|
2023-05-10 09:02:25 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
if state.Values.RootModule == nil {
|
|
|
|
return fmt.Errorf("malformed terraform state: RootModule not set")
|
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2023-11-02 11:00:30 +00:00
|
|
|
func Load(modes ...loadMode) bundle.Mutator {
|
|
|
|
return &load{modes: modes}
|
2022-12-15 14:12:47 +00:00
|
|
|
}
|