read state lock info and lock holder from environment variables

The defult LockInfo object created by terraform duirng state lock does
not use the Info field present in StateLock object that is useful for
storing metadata. Neither does the it effectively set the Who field.
Currently the Who field default to user@host. Which isn't useful when
the lock is being created from inside a docker image or in a CI/CD
pipeline. In those cases, the user might find it userful if the Who
field was instead configurable.

This commit adds the feature of reading Info and Who fields for the
LockInfo object from the TF_LOCK_METADATA and TF_LOCK_OWNER_ID
environment variables if present.
This commit is contained in:
hsiam261 2023-11-17 18:44:47 +06:00
parent f4a5b11dc1
commit a1905dd15f

View file

@ -140,6 +140,17 @@ type LockInfo struct {
Path string
}
// If this env is set, the default lockInfo Object will populate its Info field
// from this environment variable. If this environment variable is not set, this
// field will not be set as well.
const tfLockMetadataEnvName = "TF_LOCK_METADATA"
// If this env is set, the default lockInfo Object will populate its Who field
// from this environment variable and if not set, the field will defualt to
// user@host. If there is an error while reading user, it will set the empty
// string as the default value of user. Same goes for host.
const tfLockOwnerIdEnvName = "TF_LOCK_OWNER_ID"
// NewLockInfo creates a LockInfo object and populates many of its fields
// with suitable default values.
func NewLockInfo() *LockInfo {
@ -162,12 +173,24 @@ func NewLockInfo() *LockInfo {
}
host, _ := os.Hostname()
//read lock owner id from TF_LOCK_OWNER_ID
who := fmt.Sprintf("%s@%s", userName, host)
if val, present := os.LookupEnv(tfLockOwnerIdEnvName); present {
who = val
}
info := &LockInfo{
ID: id,
Who: fmt.Sprintf("%s@%s", userName, host),
Who: who,
Version: version.Version,
Created: time.Now().UTC(),
}
// read lock metadata from TF_LOCK_METADATA
if metadata, metadataPresent := os.LookupEnv(tfLockMetadataEnvName); metadataPresent {
info.Info = metadata
}
return info
}