2023-05-16 15:02:33 +00:00
|
|
|
package terraform
|
|
|
|
|
|
|
|
import (
|
2024-05-01 08:22:35 +00:00
|
|
|
"context"
|
2023-05-16 15:02:33 +00:00
|
|
|
"encoding/json"
|
2024-05-01 08:22:35 +00:00
|
|
|
"errors"
|
|
|
|
"os"
|
|
|
|
"path/filepath"
|
|
|
|
|
|
|
|
"github.com/databricks/cli/bundle"
|
|
|
|
tfjson "github.com/hashicorp/terraform-json"
|
2023-05-16 15:02:33 +00:00
|
|
|
)
|
|
|
|
|
2024-05-01 08:22:35 +00:00
|
|
|
// Partial representation of the Terraform state file format.
|
|
|
|
// We are only interested global version and serial numbers,
|
|
|
|
// plus resource types, names, modes, and ids.
|
|
|
|
type resourcesState struct {
|
|
|
|
Version int `json:"version"`
|
|
|
|
Resources []stateResource `json:"resources"`
|
|
|
|
}
|
|
|
|
|
|
|
|
const SupportedStateVersion = 4
|
|
|
|
|
|
|
|
type stateResource struct {
|
|
|
|
Type string `json:"type"`
|
|
|
|
Name string `json:"name"`
|
|
|
|
Mode tfjson.ResourceMode `json:"mode"`
|
|
|
|
Instances []stateResourceInstance `json:"instances"`
|
|
|
|
}
|
|
|
|
|
|
|
|
type stateResourceInstance struct {
|
|
|
|
Attributes stateInstanceAttributes `json:"attributes"`
|
|
|
|
}
|
|
|
|
|
|
|
|
type stateInstanceAttributes struct {
|
|
|
|
ID string `json:"id"`
|
|
|
|
}
|
|
|
|
|
|
|
|
func ParseResourcesState(ctx context.Context, b *bundle.Bundle) (*resourcesState, error) {
|
|
|
|
cacheDir, err := Dir(ctx, b)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
rawState, err := os.ReadFile(filepath.Join(cacheDir, TerraformStateFileName))
|
|
|
|
if err != nil {
|
|
|
|
if errors.Is(err, os.ErrNotExist) {
|
|
|
|
return &resourcesState{Version: SupportedStateVersion}, nil
|
|
|
|
}
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
var state resourcesState
|
|
|
|
err = json.Unmarshal(rawState, &state)
|
|
|
|
return &state, err
|
|
|
|
}
|