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.
This commit is contained in:
James Bardin 2017-08-01 17:25:24 -04:00
parent 5deef9621d
commit 18d71f273e
1 changed files with 21 additions and 0 deletions

View File

@ -12,6 +12,7 @@ import (
"github.com/hashicorp/terraform/helper/schema" "github.com/hashicorp/terraform/helper/schema"
"github.com/hashicorp/terraform/state" "github.com/hashicorp/terraform/state"
"github.com/hashicorp/terraform/state/remote" "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 // 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 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 return s, nil