states

package
v1.4.3 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Mar 29, 2023 License: MPL-2.0 Imports: 18 Imported by: 0

Documentation

Overview

Package states contains the types that are used to represent Terraform states.

Index

Constants

View Source
const NotDeposed = DeposedKey("")

NotDeposed is a special invalid value of DeposedKey that is used to represent the absense of a deposed key. It must not be used as an actual deposed key.

Variables

This section is empty.

Functions

func LegacyInstanceObjectID

func LegacyInstanceObjectID(obj *ResourceInstanceObjectSrc) string

LegacyInstanceObjectID is a helper for extracting an object id value from an instance object in a way that approximates how we used to do this for the old state types. ID is no longer first-class, so this is preserved only for compatibility with old tests that include the id as part of their expected value.

Types

type CheckResultAggregate added in v1.3.0

type CheckResultAggregate struct {
	// Status is the aggregate status across all objects.
	//
	// Sometimes an error or check failure during planning will prevent
	// Terraform Core from even determining the individual checkable objects
	// associated with a downstream configuration object, and that situation is
	// described here by this Status being checks.StatusUnknown and there being
	// no elements in the ObjectResults field.
	//
	// That's different than Terraform Core explicitly reporting that there are
	// no instances of the config object (e.g. a resource with count = 0),
	// which leads to the aggregate status being checks.StatusPass while
	// ObjectResults is still empty.
	Status checks.Status

	ObjectResults addrs.Map[addrs.Checkable, *CheckResultObject]
}

CheckResultAggregate represents both the overall result for a particular configured object that has checks and the individual checkable objects it declared, if any.

func (*CheckResultAggregate) ObjectAddrsKnown added in v1.3.0

func (r *CheckResultAggregate) ObjectAddrsKnown() bool

ObjectAddrsKnown determines whether the set of objects recorded in this aggregate is accurate (true) or if it's incomplete as a result of the run being interrupted before instance expansion.

type CheckResultObject added in v1.3.0

type CheckResultObject struct {
	// Status is the check status of the checkable object, derived from the
	// results of all of its individual checks.
	Status checks.Status

	// FailureMessages is an optional set of module-author-defined messages
	// describing the problems that the checks detected, for objects whose
	// status is checks.StatusFail.
	//
	// (checks.StatusError problems get reported as normal diagnostics during
	// evaluation instead, and so will not appear here.)
	FailureMessages []string
}

CheckResultObject is the check status for a single checkable object.

This aggregates together all of the checks associated with a particular object into a single pass/fail/error/unknown result, because checkable objects have durable addresses that can survive between runs, but their individual checks do not. (Module authors are free to reorder their checks for a particular object in the configuration with no change in meaning.)

type CheckResults added in v1.3.0

type CheckResults struct {
	// ConfigResults has all of the individual check results grouped by the
	// configuration object they relate to.
	//
	// The top-level map here will always have a key for every configuration
	// object that includes checks at the time of evaluating the results,
	// even if there turned out to be no instances of that object and
	// therefore no individual check results.
	ConfigResults addrs.Map[addrs.ConfigCheckable, *CheckResultAggregate]
}

CheckResults represents a summary snapshot of the status of a set of checks declared in configuration, updated after each Terraform Core run that changes the state or remote system in a way that might impact the check results.

Unlike a checks.State, this type only tracks the overall results for each checkable object and doesn't aim to preserve the identity of individual checks in the configuration. For our UI reporting purposes, it is entire objects that pass or fail based on their declared checks; the individual checks have no durable identity between runs, and so are only a language design convenience to help authors describe various independent conditions with different failure messages each.

CheckResults should typically be considered immutable once constructed: instead of updating it in-place,instead construct an entirely new CheckResults object based on a fresh checks.State.

func NewCheckResults added in v1.3.0

func NewCheckResults(source *checks.State) *CheckResults

NewCheckResults constructs a new states.CheckResults object that is a snapshot of the check statuses recorded in the given checks.State object.

This should be called only after a Terraform Core run has completed and recorded any results from running the checks in the given object.

func (*CheckResults) DeepCopy added in v1.3.0

func (r *CheckResults) DeepCopy() *CheckResults

func (*CheckResults) GetObjectResult added in v1.3.0

func (r *CheckResults) GetObjectResult(objectAddr addrs.Checkable) *CheckResultObject

GetObjectResult looks up the result for a single object, or nil if there is no such object.

In main code we shouldn't typically need to look up individual objects like this, since we'll usually be reporting check results in an aggregate form, but determining the result of a particular object is useful in our internal unit tests, and so this is here primarily for that purpose.

type DeposedKey

type DeposedKey string

DeposedKey is a 8-character hex string used to uniquely identify deposed instance objects in the state.

func NewDeposedKey

func NewDeposedKey() DeposedKey

NewDeposedKey generates a pseudo-random deposed key. Because of the short length of these keys, uniqueness is not a natural consequence and so the caller should test to see if the generated key is already in use and generate another if so, until a unique key is found.

func (DeposedKey) Generation

func (k DeposedKey) Generation() Generation

Generation is a helper method to convert a DeposedKey into a Generation. If the reciever is anything other than NotDeposed then the result is just the same value as a Generation. If the receiver is NotDeposed then the result is CurrentGen.

func (DeposedKey) GoString

func (k DeposedKey) GoString() string

func (DeposedKey) String

func (k DeposedKey) String() string

type Generation

type Generation interface {
	// contains filtered or unexported methods
}

Generation is used to represent multiple objects in a succession of objects represented by a single resource instance address. A resource instance can have multiple generations over its lifetime due to object replacement (when a change can't be applied without destroying and re-creating), and multiple generations can exist at the same time when create_before_destroy is used.

A Generation value can either be the value of the variable "CurrentGen" or a value of type DeposedKey. Generation values can be compared for equality using "==" and used as map keys. The zero value of Generation (nil) is not a valid generation and must not be used.

var CurrentGen Generation

CurrentGen is the Generation representing the currently-active object for a resource instance.

type Module

type Module struct {
	Addr addrs.ModuleInstance

	// Resources contains the state for each resource. The keys in this map are
	// an implementation detail and must not be used by outside callers.
	Resources map[string]*Resource

	// OutputValues contains the state for each output value. The keys in this
	// map are output value names.
	OutputValues map[string]*OutputValue

	// LocalValues contains the value for each named output value. The keys
	// in this map are local value names.
	LocalValues map[string]cty.Value
}

Module is a container for the states of objects within a particular module.

func NewModule

func NewModule(addr addrs.ModuleInstance) *Module

NewModule constructs an empty module state for the given module address.

func (*Module) DeepCopy

func (ms *Module) DeepCopy() *Module

DeepCopy returns a new module state that contains equivalent data to the receiver but shares no backing memory in common.

As with all methods on Module, this method is not safe to use concurrently with writing to any portion of the recieving data structure. It is the caller's responsibility to ensure mutual exclusion for the duration of the operation, but may then freely modify the receiver and the returned copy independently once this method returns.

func (*Module) ForgetResourceInstanceAll

func (ms *Module) ForgetResourceInstanceAll(addr addrs.ResourceInstance)

ForgetResourceInstanceAll removes the record of all objects associated with the specified resource instance, if present. If not present, this is a no-op.

func (*Module) ForgetResourceInstanceDeposed

func (ms *Module) ForgetResourceInstanceDeposed(addr addrs.ResourceInstance, key DeposedKey)

ForgetResourceInstanceDeposed removes the record of the deposed object with the given address and key, if present. If not present, this is a no-op.

func (*Module) PruneResourceHusks

func (ms *Module) PruneResourceHusks()

PruneResourceHusks is a specialized method that will remove any Resource objects that do not contain any instances, even if they have an EachMode.

You probably shouldn't call this! See the method of the same name on type State for more information on what this is for and the rare situations where it is safe to use.

func (*Module) RemoveLocalValue

func (ms *Module) RemoveLocalValue(name string)

RemoveLocalValue removes the local value of the given name from the state, if it exists. This method is a no-op if there is no value of the given name.

func (*Module) RemoveOutputValue

func (ms *Module) RemoveOutputValue(name string)

RemoveOutputValue removes the output value of the given name from the state, if it exists. This method is a no-op if there is no value of the given name.

func (*Module) RemoveResource

func (ms *Module) RemoveResource(addr addrs.Resource)

RemoveResource removes the entire state for the given resource, taking with it any instances associated with the resource. This should generally be called only for resource objects whose instances have all been destroyed.

func (*Module) Resource

func (ms *Module) Resource(addr addrs.Resource) *Resource

Resource returns the state for the resource with the given address within the receiving module state, or nil if the requested resource is not tracked in the state.

func (*Module) ResourceInstance

func (ms *Module) ResourceInstance(addr addrs.ResourceInstance) *ResourceInstance

ResourceInstance returns the state for the resource instance with the given address within the receiving module state, or nil if the requested instance is not tracked in the state.

func (*Module) SetLocalValue

func (ms *Module) SetLocalValue(name string, value cty.Value)

SetLocalValue writes a local value into the state, overwriting any existing value of the same name.

func (*Module) SetOutputValue

func (ms *Module) SetOutputValue(name string, value cty.Value, sensitive bool) *OutputValue

SetOutputValue writes an output value into the state, overwriting any existing value of the same name.

func (*Module) SetResourceInstanceCurrent

func (ms *Module) SetResourceInstanceCurrent(addr addrs.ResourceInstance, obj *ResourceInstanceObjectSrc, provider addrs.AbsProviderConfig)

SetResourceInstanceCurrent saves the given instance object as the current generation of the resource instance with the given address, simultaneously updating the recorded provider configuration address and dependencies.

Any existing current instance object for the given resource is overwritten. Set obj to nil to remove the primary generation object altogether. If there are no deposed objects then the instance will be removed altogether.

The provider address is a resource-wide setting and is updated for all other instances of the same resource as a side-effect of this call.

func (*Module) SetResourceInstanceDeposed

func (ms *Module) SetResourceInstanceDeposed(addr addrs.ResourceInstance, key DeposedKey, obj *ResourceInstanceObjectSrc, provider addrs.AbsProviderConfig)

SetResourceInstanceDeposed saves the given instance object as a deposed generation of the resource instance with the given address and deposed key.

Call this method only for pre-existing deposed objects that already have a known DeposedKey. For example, this method is useful if reloading objects that were persisted to a state file. To mark the current object as deposed, use DeposeResourceInstanceObject instead.

The resource that contains the given instance must already exist in the state, or this method will panic. Use Resource to check first if its presence is not already guaranteed.

Any existing current instance object for the given resource and deposed key is overwritten. Set obj to nil to remove the deposed object altogether. If the instance is left with no objects after this operation then it will be removed from its containing resource altogether.

func (*Module) SetResourceProvider

func (ms *Module) SetResourceProvider(addr addrs.Resource, provider addrs.AbsProviderConfig)

SetResourceProvider updates the resource-level metadata for the resource with the given address, creating the resource state for it if it doesn't already exist.

type ObjectStatus

type ObjectStatus rune

ObjectStatus represents the status of a RemoteObject.

const (
	// ObjectReady is an object status for an object that is ready to use.
	ObjectReady ObjectStatus = 'R'

	// ObjectTainted is an object status representing an object that is in
	// an unrecoverable bad state due to a partial failure during a create,
	// update, or delete operation. Since it cannot be moved into the
	// ObjectRead state, a tainted object must be replaced.
	ObjectTainted ObjectStatus = 'T'

	// ObjectPlanned is a special object status used only for the transient
	// placeholder objects we place into state during the refresh and plan
	// walks to stand in for objects that will be created during apply.
	//
	// Any object of this status must have a corresponding change recorded
	// in the current plan, whose value must then be used in preference to
	// the value stored in state when evaluating expressions. A planned
	// object stored in state will be incomplete if any of its attributes are
	// not yet known, and the plan must be consulted in order to "see" those
	// unknown values, because the state is not able to represent them.
	ObjectPlanned ObjectStatus = 'P'
)

func (ObjectStatus) String

func (i ObjectStatus) String() string

type OutputValue

type OutputValue struct {
	Addr      addrs.AbsOutputValue
	Value     cty.Value
	Sensitive bool
}

OutputValue represents the state of a particular output value.

It is not valid to mutate an OutputValue object once it has been created. Instead, create an entirely new OutputValue to replace the previous one.

func (*OutputValue) DeepCopy

func (os *OutputValue) DeepCopy() *OutputValue

DeepCopy returns a new output value state that contains equivalent data to the receiver but shares no backing memory in common.

As with all methods on OutputValue, this method is not safe to use concurrently with writing to any portion of the recieving data structure. It is the caller's responsibility to ensure mutual exclusion for the duration of the operation, but may then freely modify the receiver and the returned copy independently once this method returns.

type Resource

type Resource struct {
	// Addr is the absolute address for the resource this state object
	// belongs to.
	Addr addrs.AbsResource

	// Instances contains the potentially-multiple instances associated with
	// this resource. This map can contain a mixture of different key types,
	// but only the ones of InstanceKeyType are considered current.
	Instances map[addrs.InstanceKey]*ResourceInstance

	// ProviderConfig is the absolute address for the provider configuration that
	// most recently managed this resource. This is used to connect a resource
	// with a provider configuration when the resource configuration block is
	// not available, such as if it has been removed from configuration
	// altogether.
	ProviderConfig addrs.AbsProviderConfig
}

Resource represents the state of a resource.

func (*Resource) CreateInstance

func (rs *Resource) CreateInstance(key addrs.InstanceKey) *ResourceInstance

CreateInstance creates an instance and adds it to the resource

func (*Resource) DeepCopy

func (rs *Resource) DeepCopy() *Resource

DeepCopy returns a new resource state that contains equivalent data to the receiver but shares no backing memory in common.

As with all methods on Resource, this method is not safe to use concurrently with writing to any portion of the recieving data structure. It is the caller's responsibility to ensure mutual exclusion for the duration of the operation, but may then freely modify the receiver and the returned copy independently once this method returns.

func (*Resource) EnsureInstance

func (rs *Resource) EnsureInstance(key addrs.InstanceKey) *ResourceInstance

EnsureInstance returns the state for the instance with the given key, creating a new empty state for it if one doesn't already exist.

Because this may create and save a new state, it is considered to be a write operation.

func (*Resource) Instance

func (rs *Resource) Instance(key addrs.InstanceKey) *ResourceInstance

Instance returns the state for the instance with the given key, or nil if no such instance is tracked within the state.

type ResourceInstance

type ResourceInstance struct {
	// Current, if non-nil, is the remote object that is currently represented
	// by the corresponding resource instance.
	Current *ResourceInstanceObjectSrc

	// Deposed, if len > 0, contains any remote objects that were previously
	// represented by the corresponding resource instance but have been
	// replaced and are pending destruction due to the create_before_destroy
	// lifecycle mode.
	Deposed map[DeposedKey]*ResourceInstanceObjectSrc
}

ResourceInstance represents the state of a particular instance of a resource.

func NewResourceInstance

func NewResourceInstance() *ResourceInstance

NewResourceInstance constructs and returns a new ResourceInstance, ready to use.

func (*ResourceInstance) DeepCopy

func (i *ResourceInstance) DeepCopy() *ResourceInstance

DeepCopy returns a new resource instance state that contains equivalent data to the receiver but shares no backing memory in common.

As with all methods on ResourceInstance, this method is not safe to use concurrently with writing to any portion of the recieving data structure. It is the caller's responsibility to ensure mutual exclusion for the duration of the operation, but may then freely modify the receiver and the returned copy independently once this method returns.

func (*ResourceInstance) FindUnusedDeposedKey

func (i *ResourceInstance) FindUnusedDeposedKey() DeposedKey

FindUnusedDeposedKey generates a unique DeposedKey that is guaranteed not to already be in use for this instance at the time of the call.

Note that the validity of this result may change if new deposed keys are allocated before it is used. To avoid this risk, instead use the DeposeResourceInstanceObject method on the SyncState wrapper type, which allocates a key and uses it atomically.

func (*ResourceInstance) GetGeneration

func (i *ResourceInstance) GetGeneration(gen Generation) *ResourceInstanceObjectSrc

GetGeneration retrieves the object of the given generation from the ResourceInstance, or returns nil if there is no such object.

If the given generation is nil or invalid, this method will panic.

func (*ResourceInstance) HasAnyDeposed

func (i *ResourceInstance) HasAnyDeposed() bool

HasAnyDeposed returns true if this resource instance has one or more deposed objects.

func (*ResourceInstance) HasCurrent

func (i *ResourceInstance) HasCurrent() bool

HasCurrent returns true if this resource instance has a "current"-generation object. Most instances do, but this can briefly be false during a create-before-destroy replace operation when the current has been deposed but its replacement has not yet been created.

func (*ResourceInstance) HasDeposed

func (i *ResourceInstance) HasDeposed(key DeposedKey) bool

HasDeposed returns true if this resource instance has a deposed object with the given key.

func (*ResourceInstance) HasObjects

func (i *ResourceInstance) HasObjects() bool

HasObjects returns true if this resource has any objects at all, whether current or deposed.

type ResourceInstanceObject

type ResourceInstanceObject struct {
	// Value is the object-typed value representing the remote object within
	// Terraform.
	Value cty.Value

	// Private is an opaque value set by the provider when this object was
	// last created or updated. Terraform Core does not use this value in
	// any way and it is not exposed anywhere in the user interface, so
	// a provider can use it for retaining any necessary private state.
	Private []byte

	// Status represents the "readiness" of the object as of the last time
	// it was updated.
	Status ObjectStatus

	// Dependencies is a set of absolute address to other resources this
	// instance dependeded on when it was applied. This is used to construct
	// the dependency relationships for an object whose configuration is no
	// longer available, such as if it has been removed from configuration
	// altogether, or is now deposed.
	Dependencies []addrs.ConfigResource

	// CreateBeforeDestroy reflects the status of the lifecycle
	// create_before_destroy option when this instance was last updated.
	// Because create_before_destroy also effects the overall ordering of the
	// destroy operations, we need to record the status to ensure a resource
	// removed from the config will still be destroyed in the same manner.
	CreateBeforeDestroy bool
}

ResourceInstanceObject is the local representation of a specific remote object associated with a resource instance. In practice not all remote objects are actually remote in the sense of being accessed over the network, but this is the most common case.

It is not valid to mutate a ResourceInstanceObject once it has been created. Instead, create a new object and replace the existing one.

func (*ResourceInstanceObject) AsTainted

AsTainted returns a deep copy of the receiver with the status updated to ObjectTainted.

func (*ResourceInstanceObject) DeepCopy

DeepCopy returns a new resource instance object that contains equivalent data to the receiver but shares no backing memory in common.

As with all methods on ResourceInstanceObject, this method is not safe to use concurrently with writing to any portion of the recieving data structure. It is the caller's responsibility to ensure mutual exclusion for the duration of the operation, but may then freely modify the receiver and the returned copy independently once this method returns.

func (*ResourceInstanceObject) Encode

func (o *ResourceInstanceObject) Encode(ty cty.Type, schemaVersion uint64) (*ResourceInstanceObjectSrc, error)

Encode marshals the value within the receiver to produce a ResourceInstanceObjectSrc ready to be written to a state file.

The given type must be the implied type of the resource type schema, and the given value must conform to it. It is important to pass the schema type and not the object's own type so that dynamically-typed attributes will be stored correctly. The caller must also provide the version number of the schema that the given type was derived from, which will be recorded in the source object so it can be used to detect when schema migration is required on read.

The returned object may share internal references with the receiver and so the caller must not mutate the receiver any further once once this method is called.

type ResourceInstanceObjectSrc

type ResourceInstanceObjectSrc struct {
	// SchemaVersion is the resource-type-specific schema version number that
	// was current when either AttrsJSON or AttrsFlat was encoded. Migration
	// steps are required if this is less than the current version number
	// reported by the corresponding provider.
	SchemaVersion uint64

	// AttrsJSON is a JSON-encoded representation of the object attributes,
	// encoding the value (of the object type implied by the associated resource
	// type schema) that represents this remote object in Terraform Language
	// expressions, and is compared with configuration when producing a diff.
	//
	// This is retained in JSON format here because it may require preprocessing
	// before decoding if, for example, the stored attributes are for an older
	// schema version which the provider must upgrade before use. If the
	// version is current, it is valid to simply decode this using the
	// type implied by the current schema, without the need for the provider
	// to perform an upgrade first.
	//
	// When writing a ResourceInstanceObject into the state, AttrsJSON should
	// always be conformant to the current schema version and the current
	// schema version should be recorded in the SchemaVersion field.
	AttrsJSON []byte

	// AttrsFlat is a legacy form of attributes used in older state file
	// formats, and in the new state format for objects that haven't yet been
	// upgraded. This attribute is mutually exclusive with Attrs: for any
	// ResourceInstanceObject, only one of these attributes may be populated
	// and the other must be nil.
	//
	// An instance object with this field populated should be upgraded to use
	// Attrs at the earliest opportunity, since this legacy flatmap-based
	// format will be phased out over time. AttrsFlat should not be used when
	// writing new or updated objects to state; instead, callers must follow
	// the recommendations in the AttrsJSON documentation above.
	AttrsFlat map[string]string

	// AttrSensitivePaths is an array of paths to mark as sensitive coming out of
	// state, or to save as sensitive paths when saving state
	AttrSensitivePaths []cty.PathValueMarks

	// These fields all correspond to the fields of the same name on
	// ResourceInstanceObject.
	Private             []byte
	Status              ObjectStatus
	Dependencies        []addrs.ConfigResource
	CreateBeforeDestroy bool
}

ResourceInstanceObjectSrc is a not-fully-decoded version of ResourceInstanceObject. Decoding of it can be completed by first handling any schema migration steps to get to the latest schema version and then calling method Decode with the implied type of the latest schema.

func (*ResourceInstanceObjectSrc) CompleteUpgrade

func (os *ResourceInstanceObjectSrc) CompleteUpgrade(newAttrs cty.Value, newType cty.Type, newSchemaVersion uint64) (*ResourceInstanceObjectSrc, error)

CompleteUpgrade creates a new ResourceInstanceObjectSrc by copying the metadata from the receiver and writing in the given new schema version and attribute value that are presumed to have resulted from upgrading from an older schema version.

func (*ResourceInstanceObjectSrc) Decode

Decode unmarshals the raw representation of the object attributes. Pass the implied type of the corresponding resource type schema for correct operation.

Before calling Decode, the caller must check that the SchemaVersion field exactly equals the version number of the schema whose implied type is being passed, or else the result is undefined.

The returned object may share internal references with the receiver and so the caller must not mutate the receiver any further once once this method is called.

func (*ResourceInstanceObjectSrc) DeepCopy

DeepCopy returns a new resource instance object that contains equivalent data to the receiver but shares no backing memory in common.

As with all methods on ResourceInstanceObjectSrc, this method is not safe to use concurrently with writing to any portion of the recieving data structure. It is the caller's responsibility to ensure mutual exclusion for the duration of the operation, but may then freely modify the receiver and the returned copy independently once this method returns.

type State

type State struct {
	// Modules contains the state for each module. The keys in this map are
	// an implementation detail and must not be used by outside callers.
	Modules map[string]*Module

	// CheckResults contains a snapshot of the statuses of checks at the
	// end of the most recent update to the state. Callers might compare
	// checks between runs to see if e.g. a previously-failing check has
	// been fixed since the last run, or similar.
	//
	// CheckResults can be nil to indicate that there are no check results
	// from the previous run at all, which is subtly different than the
	// previous run having affirmatively recorded that there are no checks
	// to run. For example, if this object was created from a state snapshot
	// created by a version of Terraform that didn't yet support checks
	// then this field will be nil.
	CheckResults *CheckResults
}

State is the top-level type of a Terraform state.

A state should be mutated only via its accessor methods, to ensure that invariants are preserved.

Access to State and the nested values within it is not concurrency-safe, so when accessing a State object concurrently it is the caller's responsibility to ensure that only one write is in progress at a time and that reads only occur when no write is in progress. The most common way to achieve this is to wrap the State in a SyncState and use the higher-level atomic operations supported by that type.

func BuildState

func BuildState(cb func(*SyncState)) *State

BuildState is a helper -- primarily intended for tests -- to build a state using imperative code against the StateSync type while still acting as an expression of type *State to assign into a containing struct.

func NewState

func NewState() *State

NewState constructs a minimal empty state, containing an empty root module.

func (*State) AllResourceInstanceObjectAddrs added in v1.1.0

func (s *State) AllResourceInstanceObjectAddrs() []struct {
	Instance   addrs.AbsResourceInstance
	DeposedKey DeposedKey
}

AllManagedResourceInstanceObjectAddrs returns a set of addresses for all of the leaf resource instance objects associated with managed resources that are tracked in this state.

This result is the set of objects that would be effectively "forgotten" (like "terraform state rm") if this state were totally discarded, such as by deleting a workspace. This function is intended only for reporting context in error messages, such as when we reject deleting a "non-empty" workspace as detected by s.HasManagedResourceInstanceObjects.

The ordering of the result is meaningless but consistent. DeposedKey will be NotDeposed (the zero value of DeposedKey) for any "current" objects. This method is guaranteed to return at least one item if s.HasManagedResourceInstanceObjects returns true for the same state, and to return a zero-length slice if it returns false.

func (*State) DeepCopy

func (s *State) DeepCopy() *State

DeepCopy returns a new state that contains equivalent data to the reciever but shares no backing memory in common.

As with all methods on State, this method is not safe to use concurrently with writing to any portion of the recieving data structure. It is the caller's responsibility to ensure mutual exclusion for the duration of the operation, but may then freely modify the receiver and the returned copy independently once this method returns.

func (*State) Empty

func (s *State) Empty() bool

Empty returns true if there are no resources or populated output values in the receiver. In other words, if this state could be safely replaced with the return value of NewState and be functionally equivalent.

func (*State) EnsureModule

func (s *State) EnsureModule(addr addrs.ModuleInstance) *Module

EnsureModule returns the state for the module with the given address, creating and adding a new one if necessary.

Since this might modify the state to add a new instance, it is considered to be a write operation.

func (*State) Equal

func (s *State) Equal(other *State) bool

Equal returns true if the receiver is functionally equivalent to other, including any ephemeral portions of the state that would not be included if the state were saved to files.

To test only the persistent portions of two states for equality, instead use statefile.StatesMarshalEqual.

func (*State) HasManagedResourceInstanceObjects added in v1.1.0

func (s *State) HasManagedResourceInstanceObjects() bool

HasManagedResourceInstanceObjects returns true if there is at least one resource instance object (current or deposed) associated with a managed resource in the receiving state.

A true result would suggest that just discarding this state without first destroying these objects could leave "dangling" objects in remote systems, no longer tracked by any Terraform state.

func (*State) LocalValue

func (s *State) LocalValue(addr addrs.AbsLocalValue) cty.Value

LocalValue returns the value of the named local value with the given address, or cty.NilVal if no such value is tracked in the state.

func (*State) ManagedResourcesEqual

func (s *State) ManagedResourcesEqual(other *State) bool

ManagedResourcesEqual returns true if all of the managed resources tracked in the reciever are functionally equivalent to the same tracked in the other given state.

This is a more constrained version of Equal that disregards other differences, including but not limited to changes to data resources and changes to output values.

func (*State) MaybeMoveAbsResource added in v1.1.0

func (s *State) MaybeMoveAbsResource(src, dst addrs.AbsResource) bool

MaybeMoveAbsResource moves the given src AbsResource's current state to the new dst address. This function will succeed if both the src address does not exist in state and the dst address does; the return value indicates whether or not the move occurred. This function will panic if either the src does not exist or the dst does exist (but not both).

func (*State) MaybeMoveAbsResourceInstance added in v1.1.0

func (s *State) MaybeMoveAbsResourceInstance(src, dst addrs.AbsResourceInstance) bool

MaybeMoveAbsResourceInstance moves the given src AbsResourceInstance's current state to the new dst address. This function will succeed if both the src address does not exist in state and the dst address does; the return value indicates whether or not the move occured. This function will panic if either the src does not exist or the dst does exist (but not both).

func (*State) MaybeMoveModuleInstance added in v1.1.0

func (s *State) MaybeMoveModuleInstance(src, dst addrs.ModuleInstance) bool

MaybeMoveModuleInstance moves the given src ModuleInstance's current state to the new dst address. This function will succeed if both the src address does not exist in state and the dst address does; the return value indicates whether or not the move occured. This function will panic if either the src does not exist or the dst does exist (but not both).

func (*State) Module

func (s *State) Module(addr addrs.ModuleInstance) *Module

Module returns the state for the module with the given address, or nil if the requested module is not tracked in the state.

func (*State) ModuleInstances

func (s *State) ModuleInstances(addr addrs.Module) []*Module

ModuleInstances returns the set of Module states that matches the given path.

func (*State) ModuleOutputs

func (s *State) ModuleOutputs(parentAddr addrs.ModuleInstance, module addrs.ModuleCall) []*OutputValue

ModuleOutputs returns all outputs for the given module call under the parentAddr instance.

func (*State) MoveAbsResource added in v1.1.0

func (s *State) MoveAbsResource(src, dst addrs.AbsResource)

MoveAbsResource moves the given src AbsResource's current state to the new dst address. This will panic if the src AbsResource does not exist in state, or if there is already a resource at the dst address. It is the caller's responsibility to verify the validity of the move (for example, that the src and dst are compatible types).

func (*State) MoveAbsResourceInstance added in v1.1.0

func (s *State) MoveAbsResourceInstance(src, dst addrs.AbsResourceInstance)

MoveAbsResourceInstance moves the given src AbsResourceInstance's current state to the new dst address. This will panic if the src AbsResourceInstance does not exist in state, or if there is already a resource at the dst address. It is the caller's responsibility to verify the validity of the move (for example, that the src and dst are compatible types).

func (*State) MoveModule added in v1.1.0

func (s *State) MoveModule(src, dst addrs.AbsModuleCall)

MoveModule takes a source and destination addrs.Module address, and moves all state Modules which are contained by the src address to the new address.

func (*State) MoveModuleInstance added in v1.1.0

func (s *State) MoveModuleInstance(src, dst addrs.ModuleInstance)

MoveModuleInstance moves the given src ModuleInstance's current state to the new dst address. This will panic if the src ModuleInstance does not exist in state, or if there is already a resource at the dst address. It is the caller's responsibility to verify the validity of the move.

func (*State) OutputValue

func (s *State) OutputValue(addr addrs.AbsOutputValue) *OutputValue

OutputValue returns the state for the output value with the given address, or nil if no such output value is tracked in the state.

func (*State) ProviderAddrs

func (s *State) ProviderAddrs() []addrs.AbsProviderConfig

ProviderAddrs returns a list of all of the provider configuration addresses referenced throughout the receiving state.

The result is de-duplicated so that each distinct address appears only once.

func (*State) ProviderRequirements

func (s *State) ProviderRequirements() getproviders.Requirements

ProviderRequirements returns a description of all of the providers that are required to work with the receiving state.

Because the state does not track specific version information for providers, the requirements returned by this method will always be unconstrained. The result should usually be merged with a Requirements derived from the current configuration in order to apply some constraints.

func (*State) PruneResourceHusks

func (s *State) PruneResourceHusks()

PruneResourceHusks is a specialized method that will remove any Resource objects that do not contain any instances, even if they have an EachMode.

This should generally be used only after a "terraform destroy" operation, to finalize the cleanup of the state. It is not correct to use this after other operations because if a resource has "count = 0" or "for_each" over an empty collection then we want to retain it in the state so that references to it, particularly in "strange" contexts like "terraform console", can be properly resolved.

This method MUST NOT be called concurrently with other readers and writers of the receiving state.

func (*State) RemoveModule

func (s *State) RemoveModule(addr addrs.ModuleInstance)

RemoveModule removes the module with the given address from the state, unless it is the root module. The root module cannot be deleted, and so this method will panic if that is attempted.

Removing a module implicitly discards all of the resources, outputs and local values within it, and so this should usually be done only for empty modules. For callers accessing the state through a SyncState wrapper, modules are automatically pruned if they are empty after one of their contained elements is removed.

func (*State) Resource

func (s *State) Resource(addr addrs.AbsResource) *Resource

Resource returns the state for the resource with the given address, or nil if no such resource is tracked in the state.

func (*State) ResourceInstance

func (s *State) ResourceInstance(addr addrs.AbsResourceInstance) *ResourceInstance

ResourceInstance returns the state for the resource instance with the given address, or nil if no such resource is tracked in the state.

func (*State) Resources

func (s *State) Resources(addr addrs.ConfigResource) []*Resource

Resources returns the set of resources that match the given configuration path.

func (*State) RootModule

func (s *State) RootModule() *Module

RootModule is a convenient alias for Module(addrs.RootModuleInstance).

func (*State) String

func (s *State) String() string

String returns a rather-odd string representation of the entire state.

This is intended to match the behavior of the older terraform.State.String method that is used in lots of existing tests. It should not be used in new tests: instead, use "cmp" to directly compare the state data structures and print out a diff if they do not match.

This method should never be used in non-test code, whether directly by call or indirectly via a %s or %q verb in package fmt.

func (*State) SyncWrapper

func (s *State) SyncWrapper() *SyncState

SyncWrapper returns a SyncState object wrapping the receiver.

type SyncState

type SyncState struct {
	// contains filtered or unexported fields
}

SyncState is a wrapper around State that provides concurrency-safe access to various common operations that occur during a Terraform graph walk, or other similar concurrent contexts.

When a SyncState wrapper is in use, no concurrent direct access to the underlying objects is permitted unless the caller first acquires an explicit lock, using the Lock and Unlock methods. Most callers should _not_ explicitly lock, and should instead use the other methods of this type that handle locking automatically.

Since SyncState is able to safely consolidate multiple updates into a single atomic operation, many of its methods are at a higher level than those of the underlying types, and operate on the state as a whole rather than on individual sub-structures of the state.

SyncState can only protect against races within its own methods. It cannot provide any guarantees about the order in which concurrent operations will be processed, so callers may still need to employ higher-level techniques for ensuring correct operation sequencing, such as building and walking a dependency graph.

func (*SyncState) Close added in v1.1.0

func (s *SyncState) Close() *State

Close extracts the underlying state from inside this wrapper, making the wrapper invalid for any future operations.

func (*SyncState) DeposeResourceInstanceObject

func (s *SyncState) DeposeResourceInstanceObject(addr addrs.AbsResourceInstance) DeposedKey

DeposeResourceInstanceObject moves the current instance object for the given resource instance address into the deposed set, leaving the instance without a current object.

The return value is the newly-allocated deposed key, or NotDeposed if the given instance is already lacking a current object.

If the containing module for this resource or the resource itself are not already tracked in state then there cannot be a current object for the given instance, and so NotDeposed will be returned without modifying the state at all.

func (*SyncState) DeposeResourceInstanceObjectForceKey

func (s *SyncState) DeposeResourceInstanceObjectForceKey(addr addrs.AbsResourceInstance, forcedKey DeposedKey)

DeposeResourceInstanceObjectForceKey is like DeposeResourceInstanceObject but uses a pre-allocated key. It's the caller's responsibility to ensure that there aren't any races to use a particular key; this method will panic if the given key is already in use.

func (*SyncState) DiscardCheckResults added in v1.3.0

func (s *SyncState) DiscardCheckResults()

DiscardCheckResults discards any previously-recorded check results, with the intent of preventing any references to them after they have become stale due to starting (but possibly not completing) an update.

func (*SyncState) ForgetResourceInstanceAll

func (s *SyncState) ForgetResourceInstanceAll(addr addrs.AbsResourceInstance)

ForgetResourceInstanceAll removes the record of all objects associated with the specified resource instance, if present. If not present, this is a no-op.

func (*SyncState) ForgetResourceInstanceDeposed

func (s *SyncState) ForgetResourceInstanceDeposed(addr addrs.AbsResourceInstance, key DeposedKey)

ForgetResourceInstanceDeposed removes the record of the deposed object with the given address and key, if present. If not present, this is a no-op.

func (*SyncState) LocalValue

func (s *SyncState) LocalValue(addr addrs.AbsLocalValue) cty.Value

LocalValue returns the current value associated with the given local value address.

func (*SyncState) Lock

func (s *SyncState) Lock() *State

Lock acquires an explicit lock on the state, allowing direct read and write access to the returned state object. The caller must call Unlock once access is no longer needed, and then immediately discard the state pointer pointer.

Most callers should not use this. Instead, use the concurrency-safe accessors and mutators provided directly on SyncState.

func (*SyncState) MaybeMoveAbsResource added in v1.1.0

func (s *SyncState) MaybeMoveAbsResource(src, dst addrs.AbsResource) bool

func (*SyncState) MaybeMoveModuleInstance added in v1.1.0

func (s *SyncState) MaybeMoveModuleInstance(src, dst addrs.ModuleInstance) bool

func (*SyncState) MaybeMoveResourceInstance added in v1.1.0

func (s *SyncState) MaybeMoveResourceInstance(src, dst addrs.AbsResourceInstance) bool

func (*SyncState) MaybeRestoreResourceInstanceDeposed

func (s *SyncState) MaybeRestoreResourceInstanceDeposed(addr addrs.AbsResourceInstance, key DeposedKey) bool

MaybeRestoreResourceInstanceDeposed will restore the deposed object with the given key on the specified resource as the current object for that instance if and only if that would not cause us to forget an existing current object for that instance.

Returns true if the object was restored to current, or false if no change was made at all.

func (*SyncState) Module

func (s *SyncState) Module(addr addrs.ModuleInstance) *Module

Module returns a snapshot of the state of the module instance with the given address, or nil if no such module is tracked.

The return value is a pointer to a copy of the module state, which the caller may then freely access and mutate. However, since the module state tends to be a large data structure with many child objects, where possible callers should prefer to use a more granular accessor to access a child module directly, and thus reduce the amount of copying required.

func (*SyncState) ModuleOutputs

func (s *SyncState) ModuleOutputs(parentAddr addrs.ModuleInstance, module addrs.ModuleCall) []*OutputValue

ModuleOutputs returns the set of OutputValues that matches the given path.

func (*SyncState) MoveAbsResource added in v1.1.0

func (s *SyncState) MoveAbsResource(src, dst addrs.AbsResource)

func (*SyncState) MoveModuleInstance added in v1.1.0

func (s *SyncState) MoveModuleInstance(src, dst addrs.ModuleInstance)

func (*SyncState) MoveResourceInstance added in v1.1.0

func (s *SyncState) MoveResourceInstance(src, dst addrs.AbsResourceInstance)

func (*SyncState) OutputValue

func (s *SyncState) OutputValue(addr addrs.AbsOutputValue) *OutputValue

OutputValue returns a snapshot of the state of the output value with the given address, or nil if no such output value is tracked.

The return value is a pointer to a copy of the output value state, which the caller may then freely access and mutate.

func (*SyncState) RecordCheckResults added in v1.3.0

func (s *SyncState) RecordCheckResults(checkState *checks.State)

RecordCheckResults replaces any check results already recorded in the state with a new set taken from the given check state object.

func (*SyncState) RemoveLocalValue

func (s *SyncState) RemoveLocalValue(addr addrs.AbsLocalValue)

RemoveLocalValue removes the stored value for the local value with the given address.

If this results in its containing module being empty, the module will be pruned from the state as a side-effect.

func (*SyncState) RemoveModule

func (s *SyncState) RemoveModule(addr addrs.ModuleInstance)

RemoveModule removes the entire state for the given module, taking with it any resources associated with the module. This should generally be called only for modules whose resources have all been destroyed, but that is not enforced by this method.

func (*SyncState) RemoveOutputValue

func (s *SyncState) RemoveOutputValue(addr addrs.AbsOutputValue)

RemoveOutputValue removes the stored value for the output value with the given address.

If this results in its containing module being empty, the module will be pruned from the state as a side-effect.

func (*SyncState) RemovePlannedResourceInstanceObjects

func (s *SyncState) RemovePlannedResourceInstanceObjects()

RemovePlannedResourceInstanceObjects removes from the state any resource instance objects that have the status ObjectPlanned, indiciating that they are just transient placeholders created during planning.

Note that this does not restore any "ready" or "tainted" object that might have been present before the planned object was written. The only real use for this method is in preparing the state created during a refresh walk, where we run the planning step for certain instances just to create enough information to allow correct expression evaluation within provider and data resource blocks. Discarding planned instances in that case is okay because the refresh phase only creates planned objects to stand in for objects that don't exist yet, and thus the planned object must have been absent before by definition.

func (*SyncState) RemoveResource

func (s *SyncState) RemoveResource(addr addrs.AbsResource)

RemoveResource removes the entire state for the given resource, taking with it any instances associated with the resource. This should generally be called only for resource objects whose instances have all been destroyed, but that is not enforced by this method. (Use RemoveResourceIfEmpty instead to safely check first.)

func (*SyncState) RemoveResourceIfEmpty

func (s *SyncState) RemoveResourceIfEmpty(addr addrs.AbsResource) bool

RemoveResourceIfEmpty is similar to RemoveResource but first checks to make sure there are no instances or objects left in the resource.

Returns true if the resource was removed, or false if remaining child objects prevented its removal. Returns true also if the resource was already absent, and thus no action needed to be taken.

func (*SyncState) Resource

func (s *SyncState) Resource(addr addrs.AbsResource) *Resource

Resource returns a snapshot of the state of the resource with the given address, or nil if no such resource is tracked.

The return value is a pointer to a copy of the resource state, which the caller may then freely access and mutate.

func (*SyncState) ResourceInstance

func (s *SyncState) ResourceInstance(addr addrs.AbsResourceInstance) *ResourceInstance

ResourceInstance returns a snapshot of the state the resource instance with the given address, or nil if no such instance is tracked.

The return value is a pointer to a copy of the instance state, which the caller may then freely access and mutate.

func (*SyncState) ResourceInstanceObject

func (s *SyncState) ResourceInstanceObject(addr addrs.AbsResourceInstance, gen Generation) *ResourceInstanceObjectSrc

ResourceInstanceObject returns a snapshot of the current instance object of the given generation belonging to the instance with the given address, or nil if no such object is tracked..

The return value is a pointer to a copy of the object, which the caller may then freely access and mutate.

func (*SyncState) SetLocalValue

func (s *SyncState) SetLocalValue(addr addrs.AbsLocalValue, value cty.Value)

SetLocalValue writes a given output value into the state, overwriting any existing value of the same name.

If the module containing the local value is not yet tracked in state then it will be added as a side-effect.

func (*SyncState) SetOutputValue

func (s *SyncState) SetOutputValue(addr addrs.AbsOutputValue, value cty.Value, sensitive bool)

SetOutputValue writes a given output value into the state, overwriting any existing value of the same name.

If the module containing the output is not yet tracked in state then it be added as a side-effect.

func (*SyncState) SetResourceInstanceCurrent

func (s *SyncState) SetResourceInstanceCurrent(addr addrs.AbsResourceInstance, obj *ResourceInstanceObjectSrc, provider addrs.AbsProviderConfig)

SetResourceInstanceCurrent saves the given instance object as the current generation of the resource instance with the given address, simultaneously updating the recorded provider configuration address, dependencies, and resource EachMode.

Any existing current instance object for the given resource is overwritten. Set obj to nil to remove the primary generation object altogether. If there are no deposed objects then the instance as a whole will be removed, which may in turn also remove the containing module if it becomes empty.

The caller must ensure that the given ResourceInstanceObject is not concurrently mutated during this call, but may be freely used again once this function returns.

The provider address is a resource-wide settings and is updated for all other instances of the same resource as a side-effect of this call.

If the containing module for this resource or the resource itself are not already tracked in state then they will be added as a side-effect.

func (*SyncState) SetResourceInstanceDeposed

func (s *SyncState) SetResourceInstanceDeposed(addr addrs.AbsResourceInstance, key DeposedKey, obj *ResourceInstanceObjectSrc, provider addrs.AbsProviderConfig)

SetResourceInstanceDeposed saves the given instance object as a deposed generation of the resource instance with the given address and deposed key.

Call this method only for pre-existing deposed objects that already have a known DeposedKey. For example, this method is useful if reloading objects that were persisted to a state file. To mark the current object as deposed, use DeposeResourceInstanceObject instead.

The caller must ensure that the given ResourceInstanceObject is not concurrently mutated during this call, but may be freely used again once this function returns.

The resource that contains the given instance must already exist in the state, or this method will panic. Use Resource to check first if its presence is not already guaranteed.

Any existing current instance object for the given resource and deposed key is overwritten. Set obj to nil to remove the deposed object altogether. If the instance is left with no objects after this operation then it will be removed from its containing resource altogether.

If the containing module for this resource or the resource itself are not already tracked in state then they will be added as a side-effect.

func (*SyncState) SetResourceProvider

func (s *SyncState) SetResourceProvider(addr addrs.AbsResource, provider addrs.AbsProviderConfig)

SetResourceMeta updates the resource-level metadata for the resource at the given address, creating the containing module state and resource state as a side-effect if not already present.

func (*SyncState) Unlock

func (s *SyncState) Unlock()

Unlock releases a lock previously acquired by Lock, at which point the caller must cease all use of the state pointer that was returned.

Do not call this method except to end an explicit lock acquired by Lock. If a caller calls Unlock without first holding the lock, behavior is undefined.

Directories

Path Synopsis
Package statefile deals with the file format used to serialize states for persistent storage and then deserialize them into memory again later.
Package statefile deals with the file format used to serialize states for persistent storage and then deserialize them into memory again later.
Package statemgr defines the interfaces and some supporting functionality for "state managers", which are components responsible for writing state to some persistent storage and then later retrieving it.
Package statemgr defines the interfaces and some supporting functionality for "state managers", which are components responsible for writing state to some persistent storage and then later retrieving it.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL