-
-
Notifications
You must be signed in to change notification settings - Fork 153
Expand file tree
/
Copy pathterraform_backend_local.go
More file actions
55 lines (47 loc) · 1.89 KB
/
terraform_backend_local.go
File metadata and controls
55 lines (47 loc) · 1.89 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
package terraform_backend
import (
"fmt"
"os"
"path/filepath"
errUtils "github.com/cloudposse/atmos/errors"
"github.com/cloudposse/atmos/pkg/perf"
"github.com/cloudposse/atmos/pkg/schema"
u "github.com/cloudposse/atmos/pkg/utils"
)
// ReadTerraformBackendLocal reads the Terraform state file from the local backend.
// If the state file does not exist, the function returns `nil`.
//
// According to Terraform local backend behavior:
// - For the default workspace: state is stored at `terraform.tfstate`
// - For named workspaces: state is stored at `terraform.tfstate.d/<workspace>/terraform.tfstate`
//
// See: https://github.com/cloudposse/atmos/issues/1920
func ReadTerraformBackendLocal(
atmosConfig *schema.AtmosConfiguration,
componentSections *map[string]any,
_ *schema.AuthContext, // Auth context not used for local backend.
) ([]byte, error) {
defer perf.Track(atmosConfig, "terraform_backend.ReadTerraformBackendLocal")()
workspace := GetTerraformWorkspace(componentSections)
componentPath := filepath.Join(
atmosConfig.TerraformDirAbsolutePath,
GetTerraformComponent(componentSections),
)
var tfStateFilePath string
if workspace == "" || workspace == "default" {
// Default workspace: state is stored directly at terraform.tfstate.
tfStateFilePath = filepath.Join(componentPath, "terraform.tfstate")
} else {
// Named workspace: state is stored at terraform.tfstate.d/<workspace>/terraform.tfstate.
tfStateFilePath = filepath.Join(componentPath, "terraform.tfstate.d", workspace, "terraform.tfstate")
}
// If the state file does not exist (the component in the stack has not been provisioned yet), return a `nil` result and no error.
if !u.FileExists(tfStateFilePath) {
return nil, nil
}
content, err := os.ReadFile(tfStateFilePath)
if err != nil {
return nil, fmt.Errorf("%w.\npath: `%s`\nerror: %v", errUtils.ErrReadFile, tfStateFilePath, err)
}
return content, nil
}