From 43d000625d7c1106f1b27383775bf287b0379300 Mon Sep 17 00:00:00 2001 From: James Bardin Date: Thu, 11 Jan 2018 09:33:20 -0500 Subject: [PATCH] only split the prefix string once from the s3 key Ensure that the prefix is only split off a single time when the workspace_key_prefix is a substring of the workspace or key name. --- backend/remote-state/s3/backend_state.go | 2 +- backend/remote-state/s3/backend_test.go | 29 ++++++++++++++++++++++++ 2 files changed, 30 insertions(+), 1 deletion(-) diff --git a/backend/remote-state/s3/backend_state.go b/backend/remote-state/s3/backend_state.go index e26db42f7..842aa45a5 100644 --- a/backend/remote-state/s3/backend_state.go +++ b/backend/remote-state/s3/backend_state.go @@ -53,7 +53,7 @@ func (b *Backend) keyEnv(key string) string { } } - parts := strings.SplitAfter(key, b.workspaceKeyPrefix) + parts := strings.SplitAfterN(key, b.workspaceKeyPrefix, 2) if len(parts) < 2 { return "" diff --git a/backend/remote-state/s3/backend_test.go b/backend/remote-state/s3/backend_test.go index a86b144b5..f5e199263 100644 --- a/backend/remote-state/s3/backend_test.go +++ b/backend/remote-state/s3/backend_test.go @@ -249,6 +249,35 @@ func TestBackendExtraPaths(t *testing.T) { } } +// ensure we can separate the workspace prefix when it also matches the prefix +// of the workspace name itself. +func TestBackendPrefixInWorkspace(t *testing.T) { + testACC(t) + bucketName := fmt.Sprintf("terraform-remote-s3-test-%x", time.Now().Unix()) + + b := backend.TestBackendConfig(t, New(), map[string]interface{}{ + "bucket": bucketName, + "key": "test-env.tfstate", + "workspace_key_prefix": "env", + }).(*Backend) + + createS3Bucket(t, b.s3Client, bucketName) + defer deleteS3Bucket(t, b.s3Client, bucketName) + + // get a state that contains the prefix as a substring + sMgr, err := b.State("env-1") + if err != nil { + t.Fatal(err) + } + if err := sMgr.RefreshState(); err != nil { + t.Fatal(err) + } + + if err := checkStateList(b, []string{"default", "env-1"}); err != nil { + t.Fatal(err) + } +} + func TestKeyEnv(t *testing.T) { testACC(t) keyName := "some/paths/tfstate"