From 18d71f273e34985053aa2a8cb390361af5979e76 Mon Sep 17 00:00:00 2001 From: James Bardin Date: Tue, 1 Aug 2017 17:25:24 -0400 Subject: [PATCH] make inmem behave more like remote backends When remote backend imeplemtations create a new named state, they may need to acquire a lock and/or save an actual empty state to the backend. Copy this behavior in the inmem backend for testing. --- backend/remote-state/inmem/backend.go | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/backend/remote-state/inmem/backend.go b/backend/remote-state/inmem/backend.go index 3e66d1274..5eab8d0c6 100644 --- a/backend/remote-state/inmem/backend.go +++ b/backend/remote-state/inmem/backend.go @@ -12,6 +12,7 @@ import ( "github.com/hashicorp/terraform/helper/schema" "github.com/hashicorp/terraform/state" "github.com/hashicorp/terraform/state/remote" + "github.com/hashicorp/terraform/terraform" ) // we keep the states and locks in package-level variables, so that they can be @@ -124,6 +125,26 @@ func (b *Backend) State(name string) (state.State, error) { }, } states.m[name] = s + + // to most closely replicate other implementations, we are going to + // take a lock and create a new state if it doesn't exist. + lockInfo := state.NewLockInfo() + lockInfo.Operation = "init" + lockID, err := s.Lock(lockInfo) + if err != nil { + return nil, fmt.Errorf("failed to lock inmem state: %s", err) + } + defer s.Unlock(lockID) + + // If we have no state, we have to create an empty state + if v := s.State(); v == nil { + if err := s.WriteState(terraform.NewState()); err != nil { + return nil, err + } + if err := s.PersistState(); err != nil { + return nil, err + } + } } return s, nil