diff --git a/internal/command/add.go b/internal/command/add.go index a49adc2ee..4e23d8144 100644 --- a/internal/command/add.go +++ b/internal/command/add.go @@ -106,6 +106,14 @@ func (c *AddCommand) Run(rawArgs []string) int { return 1 } + // Successfully creating the context can result in a lock, so ensure we release it + defer func() { + diags := opReq.StateLocker.Unlock() + if diags.HasErrors() { + c.showDiagnostics(diags) + } + }() + // load the configuration to verify that the resource address doesn't // already exist in the config. var module *configs.Module diff --git a/internal/command/add_test.go b/internal/command/add_test.go index 117c55255..bfc7b6734 100644 --- a/internal/command/add_test.go +++ b/internal/command/add_test.go @@ -3,6 +3,7 @@ package command import ( "fmt" "os" + "path/filepath" "strings" "testing" @@ -592,4 +593,7 @@ resource "test_instance" "new" { t.Fatalf("wrong output:\n%s", cmp.Diff(expected, output.Stdout())) } + if _, err := os.Stat(filepath.Join(td, ".terraform.tfstate.lock.info")); !os.IsNotExist(err) { + t.Fatal("state left locked after add") + } }