tofu

package
v0.0.0-...-c924774 Latest Latest
Warning

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

Go to latest
Published: May 29, 2024 License: MPL-2.0 Imports: 36 Imported by: 0

Documentation

Index

Constants

View Source
const (
	// StateVersion is the current version for our state file
	StateVersion = 3
)

Variables

View Source
var ErrNoState = errors.New("no state")

ErrNoState is returned by ReadState when the io.Reader contains no data

Functions

func ParseResourceIndex

func ParseResourceIndex(s string) (int, error)

func ParseResourcePath

func ParseResourcePath(s string) []string

func ProviderHasDataSource

func ProviderHasDataSource(p ResourceProvider, n string) bool

func ProviderHasResource

func ProviderHasResource(p ResourceProvider, n string) bool

func ReadStateV1

func ReadStateV1(jsonBytes []byte) (*stateV1, error)

func TestStateFile

func TestStateFile(t *testing.T, path string, state *State)

TestStateFile writes the given state to the path.

func VersionString deprecated

func VersionString() string

Deprecated: Providers should use schema.Provider.TerraformVersion instead

func WriteState

func WriteState(d *State, dst io.Writer) error

WriteState writes a state somewhere in a binary format.

Types

type BackendState

type BackendState struct {
	Type      string          `json:"type"`   // Backend type
	ConfigRaw json.RawMessage `json:"config"` // Backend raw config
	Hash      uint64          `json:"hash"`   // Hash of portion of configuration from config files
}

BackendState stores the configuration to connect to a remote backend.

func (*BackendState) Config

func (s *BackendState) Config(schema *configschema.Block) (cty.Value, error)

Config decodes the type-specific configuration object using the provided schema and returns the result as a cty.Value.

An error is returned if the stored configuration does not conform to the given schema.

func (*BackendState) Empty

func (s *BackendState) Empty() bool

Empty returns true if BackendState has no state.

func (*BackendState) ForPlan

func (s *BackendState) ForPlan(schema *configschema.Block, workspaceName string) (*plans.Backend, error)

ForPlan produces an alternative representation of the reciever that is suitable for storing in a plan. The current workspace must additionally be provided, to be stored alongside the backend configuration.

The backend configuration schema is required in order to properly encode the backend-specific configuration settings.

func (*BackendState) SetConfig

func (s *BackendState) SetConfig(val cty.Value, schema *configschema.Block) error

SetConfig replaces (in-place) the type-specific configuration object using the provided value and associated schema.

An error is returned if the given value does not conform to the implied type of the schema.

type CallbackUIOutput

type CallbackUIOutput struct {
	OutputFn func(string)
}

func (*CallbackUIOutput) Output

func (o *CallbackUIOutput) Output(v string)

type DataSource

type DataSource struct {
	Name string

	// SchemaAvailable is set if the provider supports the ProviderSchema,
	// ResourceTypeSchema and DataSourceSchema methods. Although it is
	// included on each resource type, it's actually a provider-wide setting
	// that's smuggled here only because that avoids a breaking change to
	// the plugin protocol.
	SchemaAvailable bool
}

DataSource is a data source that a resource provider implements.

type Diff

type Diff struct {
	// Modules contains all the modules that have a diff
	Modules []*ModuleDiff
}

Diff tracks the changes that are necessary to apply a configuration to an existing infrastructure.

func (*Diff) AddModule

func (d *Diff) AddModule(path addrs.ModuleInstance) *ModuleDiff

AddModule adds the module with the given path to the diff.

This should be the preferred method to add module diffs since it allows us to optimize lookups later as well as control sorting.

func (*Diff) DeepCopy

func (d *Diff) DeepCopy() *Diff

DeepCopy performs a deep copy of all parts of the Diff, making the resulting Diff safe to use without modifying this one.

func (*Diff) Empty

func (d *Diff) Empty() bool

Empty returns true if the diff has no changes.

func (*Diff) Equal

func (d *Diff) Equal(d2 *Diff) bool

Equal compares two diffs for exact equality.

This is different from the Same comparison that is supported which checks for operation equality taking into account computed values. Equal instead checks for exact equality.

func (*Diff) ModuleByPath

func (d *Diff) ModuleByPath(path addrs.ModuleInstance) *ModuleDiff

ModuleByPath is used to lookup the module diff for the given path. This should be the preferred lookup mechanism as it allows for future lookup optimizations.

func (*Diff) Prune

func (d *Diff) Prune()

Prune cleans out unused structures in the diff without affecting the behavior of the diff at all.

This is not safe to call concurrently. This is safe to call on a nil Diff.

func (*Diff) RootModule

func (d *Diff) RootModule() *ModuleDiff

RootModule returns the ModuleState for the root module

func (*Diff) String

func (d *Diff) String() string

type DiffAttrType

type DiffAttrType byte

DiffAttrType is an enum type that says whether a resource attribute diff is an input attribute (comes from the configuration) or an output attribute (comes as a result of applying the configuration). An example input would be "ami" for AWS and an example output would be "private_ip".

const (
	DiffAttrUnknown DiffAttrType = iota
	DiffAttrInput
	DiffAttrOutput
)

type DiffChangeType

type DiffChangeType byte

DiffChangeType is an enum with the kind of changes a diff has planned.

const (
	DiffInvalid DiffChangeType = iota
	DiffNone
	DiffCreate
	DiffUpdate
	DiffDestroy
	DiffDestroyCreate

	// DiffRefresh is only used in the UI for displaying diffs.
	// Managed resource reads never appear in plan, and when data source
	// reads appear they are represented as DiffCreate in core before
	// transforming to DiffRefresh in the UI layer.
	DiffRefresh // TODO: Actually use DiffRefresh in core too, for less confusion
)

type EphemeralState

type EphemeralState struct {
	// ConnInfo is used for the providers to export information which is
	// used to connect to the resource for provisioning. For example,
	// this could contain SSH or WinRM credentials.
	ConnInfo map[string]string `json:"-"`

	// Type is used to specify the resource type for this instance. This is only
	// required for import operations (as documented). If the documentation
	// doesn't state that you need to set this, then don't worry about
	// setting it.
	Type string `json:"-"`
}

EphemeralState is used for transient state that is only kept in-memory

func (*EphemeralState) DeepCopy

func (e *EphemeralState) DeepCopy() *EphemeralState

type InputOpts

type InputOpts struct {
	// Id is a unique ID for the question being asked that might be
	// used for logging or to look up a prior answered question.
	Id string

	// Query is a human-friendly question for inputting this value.
	Query string

	// Description is a description about what this option is. Be wary
	// that this will probably be in a terminal so split lines as you see
	// necessary.
	Description string

	// Default will be the value returned if no data is entered.
	Default string

	// Secret should be true if we are asking for sensitive input.
	// If attached to a TTY, OpenTofu will disable echo.
	Secret bool
}

InputOpts are options for asking for input.

type InstanceDiff

type InstanceDiff struct {
	Attributes     map[string]*ResourceAttrDiff
	Destroy        bool
	DestroyDeposed bool
	DestroyTainted bool

	// Meta is a simple K/V map that is stored in a diff and persisted to
	// plans but otherwise is completely ignored by OpenTofu core. It is
	// meant to be used for additional data a resource may want to pass through.
	// The value here must only contain Go primitives and collections.
	Meta map[string]interface{}
	// contains filtered or unexported fields
}

InstanceDiff is the diff of a resource from some state to another.

func NewInstanceDiff

func NewInstanceDiff() *InstanceDiff

func (*InstanceDiff) Apply

func (d *InstanceDiff) Apply(attrs map[string]string, schema *configschema.Block) (map[string]string, error)

Apply applies the diff to the provided flatmapped attributes, returning the new instance attributes.

This method is intended for shimming old subsystems that still use this legacy diff type to work with the new-style types.

func (*InstanceDiff) ApplyToValue

func (d *InstanceDiff) ApplyToValue(base cty.Value, schema *configschema.Block) (cty.Value, error)

ApplyToValue merges the receiver into the given base value, returning a new value that incorporates the planned changes. The given value must conform to the given schema, or this method will panic.

This method is intended for shimming old subsystems that still use this legacy diff type to work with the new-style types.

func (*InstanceDiff) ChangeType

func (d *InstanceDiff) ChangeType() DiffChangeType

ChangeType returns the DiffChangeType represented by the diff for this single instance.

func (*InstanceDiff) Copy

func (d *InstanceDiff) Copy() (*InstanceDiff, error)

func (*InstanceDiff) CopyAttributes

func (d *InstanceDiff) CopyAttributes() map[string]*ResourceAttrDiff

Safely copies the Attributes map

func (*InstanceDiff) DeepCopy

func (d *InstanceDiff) DeepCopy() *InstanceDiff

DeepCopy performs a deep copy of all parts of the InstanceDiff

func (*InstanceDiff) DelAttribute

func (d *InstanceDiff) DelAttribute(key string)

func (*InstanceDiff) Empty

func (d *InstanceDiff) Empty() bool

Empty returns true if this diff encapsulates no changes.

func (*InstanceDiff) Equal

func (d *InstanceDiff) Equal(d2 *InstanceDiff) bool

Equal compares two diffs for exact equality.

This is different from the Same comparison that is supported which checks for operation equality taking into account computed values. Equal instead checks for exact equality.

func (*InstanceDiff) GetAttribute

func (d *InstanceDiff) GetAttribute(key string) (*ResourceAttrDiff, bool)

func (*InstanceDiff) GetAttributesLen

func (d *InstanceDiff) GetAttributesLen() int

func (*InstanceDiff) GetDestroy

func (d *InstanceDiff) GetDestroy() bool

func (*InstanceDiff) GetDestroyDeposed

func (d *InstanceDiff) GetDestroyDeposed() bool

func (*InstanceDiff) GetDestroyTainted

func (d *InstanceDiff) GetDestroyTainted() bool

func (*InstanceDiff) GoString

func (d *InstanceDiff) GoString() string

func (*InstanceDiff) Lock

func (d *InstanceDiff) Lock()

func (*InstanceDiff) RequiresNew

func (d *InstanceDiff) RequiresNew() bool

RequiresNew returns true if the diff requires the creation of a new resource (implying the destruction of the old).

func (*InstanceDiff) Same

func (d *InstanceDiff) Same(d2 *InstanceDiff) (bool, string)

Same checks whether or not two InstanceDiff's are the "same". When we say "same", it is not necessarily exactly equal. Instead, it is just checking that the same attributes are changing, a destroy isn't suddenly happening, etc.

func (*InstanceDiff) SetAttribute

func (d *InstanceDiff) SetAttribute(key string, attr *ResourceAttrDiff)

func (*InstanceDiff) SetDestroy

func (d *InstanceDiff) SetDestroy(b bool)

func (*InstanceDiff) SetDestroyDeposed

func (d *InstanceDiff) SetDestroyDeposed(b bool)

func (*InstanceDiff) SetTainted

func (d *InstanceDiff) SetTainted(b bool)

These methods are properly locked, for use outside other InstanceDiff methods but everywhere else within the terraform package. TODO refactor the locking scheme

func (*InstanceDiff) Unlock

func (d *InstanceDiff) Unlock()

type InstanceInfo

type InstanceInfo struct {
	// Id is a unique name to represent this instance. This is not related
	// to InstanceState.ID in any way.
	Id string

	// ModulePath is the complete path of the module containing this
	// instance.
	ModulePath []string

	// Type is the resource type of this instance
	Type string
	// contains filtered or unexported fields
}

InstanceInfo is used to hold information about the instance and/or resource being modified.

func NewInstanceInfo

func NewInstanceInfo(addr addrs.AbsResourceInstance) *InstanceInfo

NewInstanceInfo constructs an InstanceInfo from an addrs.AbsResourceInstance.

InstanceInfo is a legacy type, and uses of it should be gradually replaced by direct use of addrs.AbsResource or addrs.AbsResourceInstance as appropriate.

The legacy InstanceInfo type cannot represent module instances with instance keys, so this function will panic if given such a path. Uses of this type should all be removed or replaced before implementing "count" and "for_each" arguments on modules in order to avoid such panics.

This legacy type also cannot represent resource instances with string instance keys. It will panic if the given key is not either NoKey or an IntKey.

func (*InstanceInfo) ResourceAddress

func (i *InstanceInfo) ResourceAddress() *ResourceAddress

ResourceAddress returns the address of the resource that the receiver is describing.

type InstanceState

type InstanceState struct {
	// A unique ID for this resource. This is opaque to OpenTofu
	// and is only meant as a lookup mechanism for the providers.
	ID string `json:"id"`

	// Attributes are basic information about the resource. Any keys here
	// are accessible in variable format within OpenTofu configurations:
	// ${resourcetype.name.attribute}.
	Attributes map[string]string `json:"attributes"`

	// Ephemeral is used to store any state associated with this instance
	// that is necessary for the OpenTofu run to complete, but is not
	// persisted to a state file.
	Ephemeral EphemeralState `json:"-"`

	// Meta is a simple K/V map that is persisted to the State but otherwise
	// ignored by OpenTofu core. It's meant to be used for accounting by
	// external client code. The value here must only contain Go primitives
	// and collections.
	Meta map[string]interface{} `json:"meta"`

	ProviderMeta cty.Value

	// Tainted is used to mark a resource for recreation.
	Tainted bool `json:"tainted"`
	// contains filtered or unexported fields
}

InstanceState is used to track the unique state information belonging to a given instance.

func NewInstanceStateShimmedFromValue

func NewInstanceStateShimmedFromValue(state cty.Value, schemaVersion int) *InstanceState

NewInstanceStateShimmedFromValue is a shim method to lower a new-style object value representing the attributes of an instance object into the legacy InstanceState representation.

This is for shimming to old components only and should not be used in new code.

func (*InstanceState) AttrsAsObjectValue

func (s *InstanceState) AttrsAsObjectValue(ty cty.Type) (cty.Value, error)

AttrsAsObjectValue shims from the legacy InstanceState representation to a new-style cty object value representation of the state attributes, using the given type for guidance.

The given type must be the implied type of the schema of the resource type of the object whose state is being converted, or the result is undefined.

This is for shimming from old components only and should not be used in new code.

func (*InstanceState) DeepCopy

func (s *InstanceState) DeepCopy() *InstanceState

func (*InstanceState) Empty

func (s *InstanceState) Empty() bool

func (*InstanceState) Equal

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

func (*InstanceState) Lock

func (s *InstanceState) Lock()

func (*InstanceState) MergeDiff

func (s *InstanceState) MergeDiff(d *InstanceDiff) *InstanceState

MergeDiff takes a ResourceDiff and merges the attributes into this resource state in order to generate a new state. This new state can be used to provide updated attribute lookups for variable interpolation.

If the diff attribute requires computing the value, and hence won't be available until apply, the value is replaced with the computeID.

func (*InstanceState) Set

func (s *InstanceState) Set(from *InstanceState)

Copy all the Fields from another InstanceState

func (*InstanceState) String

func (s *InstanceState) String() string

func (*InstanceState) Unlock

func (s *InstanceState) Unlock()

type InstanceType

type InstanceType int

InstanceType is an enum of the various types of instances store in the State

const (
	TypeInvalid InstanceType = iota
	TypePrimary
	TypeTainted
	TypeDeposed
)

func ParseInstanceType

func ParseInstanceType(s string) (InstanceType, error)

func (InstanceType) String

func (i InstanceType) String() string

type MockProvider

type MockProvider struct {
	sync.Mutex

	// Anything you want, in case you need to store extra data with the mock.
	Meta interface{}

	GetSchemaCalled bool
	GetSchemaReturn *ProviderSchema // This is using ProviderSchema directly rather than providers.GetProviderSchemaResponse for compatibility with old tests

	ValidateProviderConfigCalled   bool
	ValidateProviderConfigResponse providers.ValidateProviderConfigResponse
	ValidateProviderConfigRequest  providers.ValidateProviderConfigRequest
	ValidateProviderConfigFn       func(providers.ValidateProviderConfigRequest) providers.ValidateProviderConfigResponse

	ValidateResourceConfigCalled   bool
	ValidateResourceConfigTypeName string
	ValidateResourceConfigResponse providers.ValidateResourceConfigResponse
	ValidateResourceConfigRequest  providers.ValidateResourceConfigRequest
	ValidateResourceConfigFn       func(providers.ValidateResourceConfigRequest) providers.ValidateResourceConfigResponse

	ValidateDataResourceConfigCalled   bool
	ValidateDataResourceConfigTypeName string
	ValidateDataResourceConfigResponse providers.ValidateDataResourceConfigResponse
	ValidateDataResourceConfigRequest  providers.ValidateDataResourceConfigRequest
	ValidateDataResourceConfigFn       func(providers.ValidateDataResourceConfigRequest) providers.ValidateDataResourceConfigResponse

	UpgradeResourceStateCalled   bool
	UpgradeResourceStateTypeName string
	UpgradeResourceStateResponse providers.UpgradeResourceStateResponse
	UpgradeResourceStateRequest  providers.UpgradeResourceStateRequest
	UpgradeResourceStateFn       func(providers.UpgradeResourceStateRequest) providers.UpgradeResourceStateResponse

	ConfigureProviderCalled   bool
	ConfigureProviderResponse providers.ConfigureProviderResponse
	ConfigureProviderRequest  providers.ConfigureProviderRequest
	ConfigureProviderFn       func(providers.ConfigureProviderRequest) providers.ConfigureProviderResponse

	StopCalled   bool
	StopFn       func() error
	StopResponse error

	ReadResourceCalled   bool
	ReadResourceResponse providers.ReadResourceResponse
	ReadResourceRequest  providers.ReadResourceRequest
	ReadResourceFn       func(providers.ReadResourceRequest) providers.ReadResourceResponse

	PlanResourceChangeCalled   bool
	PlanResourceChangeResponse providers.PlanResourceChangeResponse
	PlanResourceChangeRequest  providers.PlanResourceChangeRequest
	PlanResourceChangeFn       func(providers.PlanResourceChangeRequest) providers.PlanResourceChangeResponse

	ApplyResourceChangeCalled   bool
	ApplyResourceChangeResponse providers.ApplyResourceChangeResponse
	ApplyResourceChangeRequest  providers.ApplyResourceChangeRequest
	ApplyResourceChangeFn       func(providers.ApplyResourceChangeRequest) providers.ApplyResourceChangeResponse

	ImportResourceStateCalled   bool
	ImportResourceStateResponse providers.ImportResourceStateResponse
	ImportResourceStateRequest  providers.ImportResourceStateRequest
	ImportResourceStateFn       func(providers.ImportResourceStateRequest) providers.ImportResourceStateResponse
	// Legacy return type for existing tests, which will be shimmed into an
	// ImportResourceStateResponse if set
	ImportStateReturn []*InstanceState

	ReadDataSourceCalled   bool
	ReadDataSourceResponse providers.ReadDataSourceResponse
	ReadDataSourceRequest  providers.ReadDataSourceRequest
	ReadDataSourceFn       func(providers.ReadDataSourceRequest) providers.ReadDataSourceResponse

	CloseCalled bool
	CloseError  error
}

MockProvider implements providers.Interface but mocks out all the calls for testing purposes.

func (*MockProvider) Close

func (p *MockProvider) Close() error

func (*MockProvider) GetFunctions

func (p *MockProvider) GetFunctions() providers.GetFunctionsResponse

func (*MockProvider) GetProviderSchema

func (p *MockProvider) GetProviderSchema() providers.GetProviderSchemaResponse

func (*MockProvider) Stop

func (p *MockProvider) Stop() error

type MockProvisioner

type MockProvisioner struct {
	sync.Mutex
	// Anything you want, in case you need to store extra data with the mock.
	Meta interface{}

	GetSchemaCalled   bool
	GetSchemaResponse provisioners.GetSchemaResponse

	ValidateProvisionerConfigCalled   bool
	ValidateProvisionerConfigRequest  provisioners.ValidateProvisionerConfigRequest
	ValidateProvisionerConfigResponse provisioners.ValidateProvisionerConfigResponse
	ValidateProvisionerConfigFn       func(provisioners.ValidateProvisionerConfigRequest) provisioners.ValidateProvisionerConfigResponse

	ProvisionResourceCalled   bool
	ProvisionResourceRequest  provisioners.ProvisionResourceRequest
	ProvisionResourceResponse provisioners.ProvisionResourceResponse
	ProvisionResourceFn       func(provisioners.ProvisionResourceRequest) provisioners.ProvisionResourceResponse

	StopCalled   bool
	StopResponse error
	StopFn       func() error

	CloseCalled   bool
	CloseResponse error
	CloseFn       func() error
}

MockProvisioner implements provisioners.Interface but mocks out all the calls for testing purposes.

func (*MockProvisioner) Close

func (p *MockProvisioner) Close() error

func (*MockProvisioner) GetSchema

func (*MockProvisioner) Stop

func (p *MockProvisioner) Stop() error

type MockResourceProvider

type MockResourceProvider struct {
	sync.Mutex

	// Anything you want, in case you need to store extra data with the mock.
	Meta interface{}

	CloseCalled                    bool
	CloseError                     error
	GetSchemaCalled                bool
	GetSchemaRequest               *ProviderSchemaRequest
	GetSchemaReturn                *ProviderSchema
	GetSchemaReturnError           error
	InputCalled                    bool
	InputInput                     UIInput
	InputConfig                    *ResourceConfig
	InputReturnConfig              *ResourceConfig
	InputReturnError               error
	InputFn                        func(UIInput, *ResourceConfig) (*ResourceConfig, error)
	ApplyCalled                    bool
	ApplyInfo                      *InstanceInfo
	ApplyState                     *InstanceState
	ApplyDiff                      *InstanceDiff
	ApplyFn                        func(*InstanceInfo, *InstanceState, *InstanceDiff) (*InstanceState, error)
	ApplyReturn                    *InstanceState
	ApplyReturnError               error
	ConfigureCalled                bool
	ConfigureConfig                *ResourceConfig
	ConfigureProviderFn            func(*ResourceConfig) error
	ConfigureReturnError           error
	DiffCalled                     bool
	DiffInfo                       *InstanceInfo
	DiffState                      *InstanceState
	DiffDesired                    *ResourceConfig
	DiffFn                         func(*InstanceInfo, *InstanceState, *ResourceConfig) (*InstanceDiff, error)
	DiffReturn                     *InstanceDiff
	DiffReturnError                error
	RefreshCalled                  bool
	RefreshInfo                    *InstanceInfo
	RefreshState                   *InstanceState
	RefreshFn                      func(*InstanceInfo, *InstanceState) (*InstanceState, error)
	RefreshReturn                  *InstanceState
	RefreshReturnError             error
	ResourcesCalled                bool
	ResourcesReturn                []ResourceType
	ReadDataApplyCalled            bool
	ReadDataApplyInfo              *InstanceInfo
	ReadDataApplyDiff              *InstanceDiff
	ReadDataApplyFn                func(*InstanceInfo, *InstanceDiff) (*InstanceState, error)
	ReadDataApplyReturn            *InstanceState
	ReadDataApplyReturnError       error
	ReadDataDiffCalled             bool
	ReadDataDiffInfo               *InstanceInfo
	ReadDataDiffDesired            *ResourceConfig
	ReadDataDiffFn                 func(*InstanceInfo, *ResourceConfig) (*InstanceDiff, error)
	ReadDataDiffReturn             *InstanceDiff
	ReadDataDiffReturnError        error
	StopCalled                     bool
	StopFn                         func() error
	StopReturnError                error
	DataSourcesCalled              bool
	DataSourcesReturn              []DataSource
	ValidateCalled                 bool
	ValidateConfig                 *ResourceConfig
	ValidateFn                     func(*ResourceConfig) ([]string, []error)
	ValidateReturnWarns            []string
	ValidateReturnErrors           []error
	ValidateResourceFn             func(string, *ResourceConfig) ([]string, []error)
	ValidateResourceCalled         bool
	ValidateResourceType           string
	ValidateResourceConfig         *ResourceConfig
	ValidateResourceReturnWarns    []string
	ValidateResourceReturnErrors   []error
	ValidateDataSourceFn           func(string, *ResourceConfig) ([]string, []error)
	ValidateDataSourceCalled       bool
	ValidateDataSourceType         string
	ValidateDataSourceConfig       *ResourceConfig
	ValidateDataSourceReturnWarns  []string
	ValidateDataSourceReturnErrors []error

	ImportStateCalled      bool
	ImportStateInfo        *InstanceInfo
	ImportStateID          string
	ImportStateReturn      []*InstanceState
	ImportStateReturnError error
	ImportStateFn          func(*InstanceInfo, string) ([]*InstanceState, error)
}

MockResourceProvider implements ResourceProvider but mocks out all the calls for testing purposes.

func (*MockResourceProvider) Apply

func (p *MockResourceProvider) Apply(
	info *InstanceInfo,
	state *InstanceState,
	diff *InstanceDiff) (*InstanceState, error)

func (*MockResourceProvider) Close

func (p *MockResourceProvider) Close() error

func (*MockResourceProvider) Configure

func (p *MockResourceProvider) Configure(c *ResourceConfig) error

func (*MockResourceProvider) DataSources

func (p *MockResourceProvider) DataSources() []DataSource

func (*MockResourceProvider) Diff

func (p *MockResourceProvider) Diff(
	info *InstanceInfo,
	state *InstanceState,
	desired *ResourceConfig) (*InstanceDiff, error)

func (*MockResourceProvider) GetSchema

func (*MockResourceProvider) ImportState

func (p *MockResourceProvider) ImportState(info *InstanceInfo, id string) ([]*InstanceState, error)

func (*MockResourceProvider) Input

func (*MockResourceProvider) ReadDataApply

func (p *MockResourceProvider) ReadDataApply(
	info *InstanceInfo,
	d *InstanceDiff) (*InstanceState, error)

func (*MockResourceProvider) ReadDataDiff

func (p *MockResourceProvider) ReadDataDiff(
	info *InstanceInfo,
	desired *ResourceConfig) (*InstanceDiff, error)

func (*MockResourceProvider) Refresh

func (*MockResourceProvider) Resources

func (p *MockResourceProvider) Resources() []ResourceType

func (*MockResourceProvider) Stop

func (p *MockResourceProvider) Stop() error

func (*MockResourceProvider) Validate

func (p *MockResourceProvider) Validate(c *ResourceConfig) ([]string, []error)

func (*MockResourceProvider) ValidateDataSource

func (p *MockResourceProvider) ValidateDataSource(t string, c *ResourceConfig) ([]string, []error)

func (*MockResourceProvider) ValidateResource

func (p *MockResourceProvider) ValidateResource(t string, c *ResourceConfig) ([]string, []error)

type MockResourceProvisioner

type MockResourceProvisioner struct {
	sync.Mutex
	// Anything you want, in case you need to store extra data with the mock.
	Meta interface{}

	GetConfigSchemaCalled       bool
	GetConfigSchemaReturnSchema *configschema.Block
	GetConfigSchemaReturnError  error

	ApplyCalled      bool
	ApplyOutput      UIOutput
	ApplyState       *InstanceState
	ApplyConfig      *ResourceConfig
	ApplyFn          func(*InstanceState, *ResourceConfig) error
	ApplyReturnError error

	ValidateCalled       bool
	ValidateConfig       *ResourceConfig
	ValidateFn           func(c *ResourceConfig) ([]string, []error)
	ValidateReturnWarns  []string
	ValidateReturnErrors []error

	StopCalled      bool
	StopFn          func() error
	StopReturnError error
}

MockResourceProvisioner implements ResourceProvisioner but mocks out all the calls for testing purposes.

func (*MockResourceProvisioner) Apply

func (p *MockResourceProvisioner) Apply(
	output UIOutput,
	state *InstanceState,
	c *ResourceConfig) error

func (*MockResourceProvisioner) GetConfigSchema

func (p *MockResourceProvisioner) GetConfigSchema() (*configschema.Block, error)

func (*MockResourceProvisioner) Stop

func (p *MockResourceProvisioner) Stop() error

func (*MockResourceProvisioner) Validate

func (p *MockResourceProvisioner) Validate(c *ResourceConfig) ([]string, []error)

type MockUIInput

type MockUIInput struct {
	InputCalled       bool
	InputOpts         *InputOpts
	InputReturnMap    map[string]string
	InputReturnString string
	InputReturnError  error
	InputFn           func(*InputOpts) (string, error)
}

MockUIInput is an implementation of UIInput that can be used for tests.

func (*MockUIInput) Input

func (i *MockUIInput) Input(ctx context.Context, opts *InputOpts) (string, error)

type MockUIOutput

type MockUIOutput struct {
	sync.Mutex
	OutputCalled  bool
	OutputMessage string
	OutputFn      func(string)
}

MockUIOutput is an implementation of UIOutput that can be used for tests.

func (*MockUIOutput) Output

func (o *MockUIOutput) Output(v string)

type ModuleDiff

type ModuleDiff struct {
	Path      []string
	Resources map[string]*InstanceDiff
	Destroy   bool // Set only by the destroy plan
}

ModuleDiff tracks the differences between resources to apply within a single module.

func (*ModuleDiff) ChangeType

func (d *ModuleDiff) ChangeType() DiffChangeType

ChangeType returns the type of changes that the diff for this module includes.

At a module level, this will only be DiffNone, DiffUpdate, DiffDestroy, or DiffCreate. If an instance within the module has a DiffDestroyCreate then this will register as a DiffCreate for a module.

func (*ModuleDiff) Empty

func (d *ModuleDiff) Empty() bool

Empty returns true if the diff has no changes within this module.

func (*ModuleDiff) Instances

func (d *ModuleDiff) Instances(id string) []*InstanceDiff

Instances returns the instance diffs for the id given. This can return multiple instance diffs if there are counts within the resource.

func (*ModuleDiff) IsRoot

func (d *ModuleDiff) IsRoot() bool

IsRoot says whether or not this module diff is for the root module.

func (*ModuleDiff) String

func (d *ModuleDiff) String() string

String outputs the diff in a long but command-line friendly output format that users can read to quickly inspect a diff.

type ModuleState

type ModuleState struct {
	// Path is the import path from the root module. Modules imports are
	// always disjoint, so the path represents amodule tree
	Path []string `json:"path"`

	// Locals are kept only transiently in-memory, because we can always
	// re-compute them.
	Locals map[string]interface{} `json:"-"`

	// Outputs declared by the module and maintained for each module
	// even though only the root module technically needs to be kept.
	// This allows operators to inspect values at the boundaries.
	Outputs map[string]*OutputState `json:"outputs"`

	// Resources is a mapping of the logically named resource to
	// the state of the resource. Each resource may actually have
	// N instances underneath, although a user only needs to think
	// about the 1:1 case.
	Resources map[string]*ResourceState `json:"resources"`

	// Dependencies are a list of things that this module relies on
	// existing to remain intact. For example: an module may depend
	// on a VPC ID given by an aws_vpc resource.
	//
	// OpenTofu uses this information to build valid destruction
	// orders and to warn the user if they're destroying a module that
	// another resource depends on.
	//
	// Things can be put into this list that may not be managed by
	// OpenTofu. If OpenTofu doesn't find a matching ID in the
	// overall state, then it assumes it isn't managed and doesn't
	// worry about it.
	Dependencies []string `json:"depends_on"`
	// contains filtered or unexported fields
}

ModuleState is used to track all the state relevant to a single module. Previous to Terraform 0.3, all state belonged to the "root" module.

func (*ModuleState) Empty

func (m *ModuleState) Empty() bool

func (*ModuleState) Equal

func (m *ModuleState) Equal(other *ModuleState) bool

Equal tests whether one module state is equal to another.

func (*ModuleState) IsDescendent

func (m *ModuleState) IsDescendent(other *ModuleState) bool

IsDescendent returns true if other is a descendent of this module.

func (*ModuleState) IsRoot

func (m *ModuleState) IsRoot() bool

IsRoot says whether or not this module diff is for the root module.

func (*ModuleState) Lock

func (s *ModuleState) Lock()

func (*ModuleState) Orphans

func (m *ModuleState) Orphans(c *configs.Module) []addrs.ResourceInstance

Orphans returns a list of keys of resources that are in the State but aren't present in the configuration itself. Hence, these keys represent the state of resources that are orphans.

func (*ModuleState) RemovedOutputs

func (s *ModuleState) RemovedOutputs(outputs map[string]*configs.Output) []addrs.OutputValue

RemovedOutputs returns a list of outputs that are in the State but aren't present in the configuration itself.

func (*ModuleState) String

func (m *ModuleState) String() string

func (*ModuleState) Unlock

func (s *ModuleState) Unlock()

func (*ModuleState) View

func (m *ModuleState) View(id string) *ModuleState

View returns a view with the given resource prefix.

type OutputState

type OutputState struct {
	// Sensitive describes whether the output is considered sensitive,
	// which may lead to masking the value on screen in some cases.
	Sensitive bool `json:"sensitive"`
	// Type describes the structure of Value. Valid values are "string",
	// "map" and "list"
	Type string `json:"type"`
	// Value contains the value of the output, in the structure described
	// by the Type field.
	Value interface{} `json:"value"`
	// contains filtered or unexported fields
}

OutputState is used to track the state relevant to a single output.

func (*OutputState) Equal

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

Equal compares two OutputState structures for equality. nil values are considered equal.

func (*OutputState) Lock

func (s *OutputState) Lock()

func (*OutputState) String

func (s *OutputState) String() string

func (*OutputState) Unlock

func (s *OutputState) Unlock()

type PrefixUIInput

type PrefixUIInput struct {
	IdPrefix    string
	QueryPrefix string
	UIInput     UIInput
}

PrefixUIInput is an implementation of UIInput that prefixes the ID with a string, allowing queries to be namespaced.

func (*PrefixUIInput) Input

func (i *PrefixUIInput) Input(ctx context.Context, opts *InputOpts) (string, error)

type ProviderSchema

type ProviderSchema struct {
	Provider      *configschema.Block
	ProviderMeta  *configschema.Block
	ResourceTypes map[string]*configschema.Block
	DataSources   map[string]*configschema.Block

	ResourceTypeSchemaVersions map[string]uint64
}

ProviderSchema represents the schema for a provider's own configuration and the configuration for some or all of its resources and data sources.

The completeness of this structure depends on how it was constructed. When constructed for a configuration, it will generally include only resource types and data sources used by that configuration.

func (*ProviderSchema) SchemaForResourceAddr

func (ps *ProviderSchema) SchemaForResourceAddr(addr addrs.Resource) (schema *configschema.Block, version uint64)

SchemaForResourceAddr attempts to find a schema for the mode and type from the given resource address. Returns nil if no such schema is available.

func (*ProviderSchema) SchemaForResourceType

func (ps *ProviderSchema) SchemaForResourceType(mode addrs.ResourceMode, typeName string) (schema *configschema.Block, version uint64)

SchemaForResourceType attempts to find a schema for the given mode and type. Returns nil if no such schema is available.

type ProviderSchemaRequest

type ProviderSchemaRequest struct {
	ResourceTypes []string
	DataSources   []string
}

ProviderSchemaRequest is used to describe to a ResourceProvider which aspects of schema are required, when calling the GetSchema method.

type ProvisionerFactory

type ProvisionerFactory = provisioners.Factory

ProvisionerFactory is a function type that creates a new instance of a provisioners.Interface.

type RemoteState

type RemoteState struct {
	// Type controls the client we use for the remote state
	Type string `json:"type"`

	// Config is used to store arbitrary configuration that
	// is type specific
	Config map[string]string `json:"config"`
	// contains filtered or unexported fields
}

RemoteState is used to track the information about a remote state store that we push/pull state to.

func (*RemoteState) Empty

func (r *RemoteState) Empty() bool

func (*RemoteState) Equals

func (r *RemoteState) Equals(other *RemoteState) bool

func (*RemoteState) Lock

func (s *RemoteState) Lock()

func (*RemoteState) Unlock

func (s *RemoteState) Unlock()

type Resource

type Resource struct {
	// These are all used by the new EvalNode stuff.
	Name       string
	Type       string
	CountIndex int

	// These aren't really used anymore anywhere, but we keep them around
	// since we haven't done a proper cleanup yet.
	Id           string
	Info         *InstanceInfo
	Config       *ResourceConfig
	Dependencies []string
	Diff         *InstanceDiff
	Provider     ResourceProvider
	State        *InstanceState
	Flags        ResourceFlag
}

Resource is a legacy way to identify a particular resource instance.

New code should use addrs.ResourceInstance instead. This is still here only for codepaths that haven't been updated yet.

func NewResource

func NewResource(addr addrs.ResourceInstance) *Resource

NewResource constructs a legacy Resource object from an addrs.ResourceInstance value.

This is provided to shim to old codepaths that haven't been updated away from this type yet. Since this old type is not able to represent instances that have string keys, this function will panic if given a resource address that has a string key.

type ResourceAddress

type ResourceAddress struct {
	// Addresses a resource falling somewhere in the module path
	// When specified alone, addresses all resources within a module path
	Path []string

	// Addresses a specific resource that occurs in a list
	Index int

	InstanceType    InstanceType
	InstanceTypeSet bool
	Name            string
	Type            string
	Mode            ResourceMode // significant only if InstanceTypeSet
}

ResourceAddress is a way of identifying an individual resource (or, eventually, a subset of resources) within the state. It is used for Targets.

func NewLegacyResourceAddress

func NewLegacyResourceAddress(addr addrs.AbsResource) *ResourceAddress

NewLegacyResourceAddress creates a ResourceAddress from a new-style addrs.AbsResource value.

This is provided for shimming purposes so that we can still easily call into older functions that expect the ResourceAddress type.

func NewLegacyResourceInstanceAddress

func NewLegacyResourceInstanceAddress(addr addrs.AbsResourceInstance) *ResourceAddress

NewLegacyResourceInstanceAddress creates a ResourceAddress from a new-style addrs.AbsResource value.

This is provided for shimming purposes so that we can still easily call into older functions that expect the ResourceAddress type.

func ParseResourceAddress

func ParseResourceAddress(s string) (*ResourceAddress, error)

func ParseResourceAddressForInstanceDiff

func ParseResourceAddressForInstanceDiff(path []string, key string) (*ResourceAddress, error)

ParseResourceAddressForInstanceDiff creates a ResourceAddress for a resource name as described in a module diff.

For historical reasons a different addressing format is used in this context. The internal format should not be shown in the UI and instead this function should be used to translate to a ResourceAddress and then, where appropriate, use the String method to produce a canonical resource address string for display in the UI.

The given path slice must be empty (or nil) for the root module, and otherwise consist of a sequence of module names traversing down into the module tree. If a non-nil path is provided, the caller must not modify its underlying array after passing it to this function.

func (*ResourceAddress) AbsResourceInstanceAddr

func (addr *ResourceAddress) AbsResourceInstanceAddr() addrs.AbsResourceInstance

AbsResourceInstanceAddr converts the receiver, a legacy resource address, to the new resource address type addrs.AbsResourceInstance.

This method can be used only on an address that has a resource specification. It will panic if called on a module-path-only ResourceAddress. Use method HasResourceSpec to check before calling, in contexts where it is unclear.

addrs.AbsResourceInstance does not represent the "tainted" and "deposed" states, and so if these are present on the receiver then they are discarded.

This is provided for shimming purposes so that we can easily adapt functions that are returning the legacy ResourceAddress type, for situations where the new type is required.

func (*ResourceAddress) Contains

func (addr *ResourceAddress) Contains(other *ResourceAddress) bool

Contains returns true if and only if the given node is contained within the receiver.

Containment is defined in terms of the module and resource hierarchy: a resource is contained within its module and any ancestor modules, an indexed resource instance is contained with the unindexed resource, etc.

func (*ResourceAddress) Copy

func (r *ResourceAddress) Copy() *ResourceAddress

Copy returns a copy of this ResourceAddress

func (*ResourceAddress) Equals

func (addr *ResourceAddress) Equals(raw interface{}) bool

Equals returns true if the receiver matches the given address.

The name of this method is a misnomer, since it doesn't test for exact equality. Instead, it tests that the _specified_ parts of each address match, treating any unspecified parts as wildcards.

See also Contains, which takes a more hierarchical approach to comparing addresses.

func (*ResourceAddress) HasResourceSpec

func (r *ResourceAddress) HasResourceSpec() bool

HasResourceSpec returns true if the address has a resource spec, as defined in the documentation:

https://opentofu.org/docs/cli/state/resource-addressing/

In particular, this returns false if the address contains only a module path, thus addressing the entire module.

func (*ResourceAddress) Less

func (addr *ResourceAddress) Less(other *ResourceAddress) bool

Less returns true if and only if the receiver should be sorted before the given address when presenting a list of resource addresses to an end-user.

This sort uses lexicographic sorting for most components, but uses numeric sort for indices, thus causing index 10 to sort after index 9, rather than after index 1.

func (*ResourceAddress) MatchesResourceConfig

func (r *ResourceAddress) MatchesResourceConfig(path addrs.Module, rc *configs.Resource) bool

MatchesResourceConfig returns true if the receiver matches the given configuration resource within the given _static_ module path. Note that the module path in a resource address is a _dynamic_ module path, and multiple dynamic resource paths may map to a single static path if count and for_each are in use on module calls.

Since resource configuration blocks represent all of the instances of a multi-instance resource, the index of the address (if any) is not considered.

func (*ResourceAddress) ModuleInstanceAddr

func (addr *ResourceAddress) ModuleInstanceAddr() addrs.ModuleInstance

ModuleInstanceAddr returns the module path portion of the receiver as a addrs.ModuleInstance value.

func (*ResourceAddress) String

func (r *ResourceAddress) String() string

String outputs the address that parses into this address.

func (*ResourceAddress) WholeModuleAddress

func (r *ResourceAddress) WholeModuleAddress() *ResourceAddress

WholeModuleAddress returns the resource address that refers to all resources in the same module as the receiver address.

type ResourceAttrDiff

type ResourceAttrDiff struct {
	Old         string      // Old Value
	New         string      // New Value
	NewComputed bool        // True if new value is computed (unknown currently)
	NewRemoved  bool        // True if this attribute is being removed
	NewExtra    interface{} // Extra information for the provider
	RequiresNew bool        // True if change requires new resource
	Sensitive   bool        // True if the data should not be displayed in UI output
	Type        DiffAttrType
}

ResourceAttrDiff is the diff of a single attribute of a resource.

func (*ResourceAttrDiff) Empty

func (d *ResourceAttrDiff) Empty() bool

Empty returns true if the diff for this attr is neutral

func (*ResourceAttrDiff) GoString

func (d *ResourceAttrDiff) GoString() string

type ResourceConfig

type ResourceConfig struct {
	ComputedKeys []string
	Raw          map[string]interface{}
	Config       map[string]interface{}
}

ResourceConfig is a legacy type that was formerly used to represent interpolatable configuration blocks. It is now only used to shim to old APIs that still use this type, via NewResourceConfigShimmed.

func NewResourceConfigRaw

func NewResourceConfigRaw(raw map[string]interface{}) *ResourceConfig

NewResourceConfigRaw constructs a ResourceConfig whose content is exactly the given value.

The given value may contain hcl2shim.UnknownVariableValue to signal that something is computed, but it must not contain unprocessed interpolation sequences as we might've seen in Terraform v0.11 and prior.

func NewResourceConfigShimmed

func NewResourceConfigShimmed(val cty.Value, schema *configschema.Block) *ResourceConfig

NewResourceConfigShimmed wraps a cty.Value of object type in a legacy ResourceConfig object, so that it can be passed to older APIs that expect this wrapping.

The returned ResourceConfig is already interpolated and cannot be re-interpolated. It is, therefore, useful only to functions that expect an already-populated ResourceConfig which they then treat as read-only.

If the given value is not of an object type that conforms to the given schema then this function will panic.

func (*ResourceConfig) CheckSet

func (c *ResourceConfig) CheckSet(keys []string) []error

CheckSet checks that the given list of configuration keys is properly set. If not, errors are returned for each unset key.

This is useful to be called in the Validate method of a ResourceProvider.

func (*ResourceConfig) DeepCopy

func (c *ResourceConfig) DeepCopy() *ResourceConfig

DeepCopy performs a deep copy of the configuration. This makes it safe to modify any of the structures that are part of the resource config without affecting the original configuration.

func (*ResourceConfig) Equal

func (c *ResourceConfig) Equal(c2 *ResourceConfig) bool

Equal checks the equality of two resource configs.

func (*ResourceConfig) Get

func (c *ResourceConfig) Get(k string) (interface{}, bool)

Get looks up a configuration value by key and returns the value.

The second return value is true if the get was successful. Get will return the raw value if the key is computed, so you should pair this with IsComputed.

func (*ResourceConfig) GetRaw

func (c *ResourceConfig) GetRaw(k string) (interface{}, bool)

GetRaw looks up a configuration value by key and returns the value, from the raw, uninterpolated config.

The second return value is true if the get was successful. Get will not succeed if the value is being computed.

func (*ResourceConfig) IsComputed

func (c *ResourceConfig) IsComputed(k string) bool

IsComputed returns whether the given key is computed or not.

func (*ResourceConfig) IsSet

func (c *ResourceConfig) IsSet(k string) bool

IsSet checks if the key in the configuration is set. A key is set if it has a value or the value is being computed (is unknown currently).

This function should be used rather than checking the keys of the raw configuration itself, since a key may be omitted from the raw configuration if it is being computed.

type ResourceFlag

type ResourceFlag byte

ResourceFlag specifies what kind of instance we're working with, whether its a primary instance, a tainted instance, or an orphan.

type ResourceMode

type ResourceMode int

ResourceMode is deprecated, use addrs.ResourceMode instead. It has been preserved for backwards compatibility.

const (
	ManagedResourceMode ResourceMode = iota
	DataResourceMode
)

func (ResourceMode) String

func (i ResourceMode) String() string

type ResourceProvider

type ResourceProvider interface {

	// ProviderSchema returns the config schema for the main provider
	// configuration, as would appear in a "provider" block in the
	// configuration files.
	//
	// Currently not all providers support schema. Callers must therefore
	// first call Resources and DataSources and ensure that at least one
	// resource or data source has the SchemaAvailable flag set.
	GetSchema(*ProviderSchemaRequest) (*ProviderSchema, error)

	// Input was used prior to v0.12 to ask the provider to prompt the user
	// for input to complete the configuration.
	//
	// From v0.12 onwards this method is never called because OpenTofu Core
	// is able to handle the necessary input logic itself based on the
	// schema returned from GetSchema.
	Input(UIInput, *ResourceConfig) (*ResourceConfig, error)

	// Validate is called once at the beginning with the raw configuration
	// (no interpolation done) and can return a list of warnings and/or
	// errors.
	//
	// This is called once with the provider configuration only. It may not
	// be called at all if no provider configuration is given.
	//
	// This should not assume that any values of the configurations are valid.
	// The primary use case of this call is to check that required keys are
	// set.
	Validate(*ResourceConfig) ([]string, []error)

	// Configure configures the provider itself with the configuration
	// given. This is useful for setting things like access keys.
	//
	// This won't be called at all if no provider configuration is given.
	//
	// Configure returns an error if it occurred.
	Configure(*ResourceConfig) error

	// Resources returns all the available resource types that this provider
	// knows how to manage.
	Resources() []ResourceType

	// Stop is called when the provider should halt any in-flight actions.
	//
	// This can be used to make a nicer Ctrl-C experience for OpenTofu.
	// Even if this isn't implemented to do anything (just returns nil),
	// OpenTofu will still cleanly stop after the currently executing
	// graph node is complete. However, this API can be used to make more
	// efficient halts.
	//
	// Stop doesn't have to and shouldn't block waiting for in-flight actions
	// to complete. It should take any action it wants and return immediately
	// acknowledging it has received the stop request. OpenTofu core will
	// automatically not make any further API calls to the provider soon
	// after Stop is called (technically exactly once the currently executing
	// graph nodes are complete).
	//
	// The error returned, if non-nil, is assumed to mean that signaling the
	// stop somehow failed and that the user should expect potentially waiting
	// a longer period of time.
	Stop() error

	// ValidateResource is called once at the beginning with the raw
	// configuration (no interpolation done) and can return a list of warnings
	// and/or errors.
	//
	// This is called once per resource.
	//
	// This should not assume any of the values in the resource configuration
	// are valid since it is possible they have to be interpolated still.
	// The primary use case of this call is to check that the required keys
	// are set and that the general structure is correct.
	ValidateResource(string, *ResourceConfig) ([]string, []error)

	// Apply applies a diff to a specific resource and returns the new
	// resource state along with an error.
	//
	// If the resource state given has an empty ID, then a new resource
	// is expected to be created.
	Apply(
		*InstanceInfo,
		*InstanceState,
		*InstanceDiff) (*InstanceState, error)

	// Diff diffs a resource versus a desired state and returns
	// a diff.
	Diff(
		*InstanceInfo,
		*InstanceState,
		*ResourceConfig) (*InstanceDiff, error)

	// Refresh refreshes a resource and updates all of its attributes
	// with the latest information.
	Refresh(*InstanceInfo, *InstanceState) (*InstanceState, error)

	// ImportState requests that the given resource be imported.
	//
	// The returned InstanceState only requires ID be set. Importing
	// will always call Refresh after the state to complete it.
	//
	// IMPORTANT: InstanceState doesn't have the resource type attached
	// to it. A type must be specified on the state via the Ephemeral
	// field on the state.
	//
	// This function can return multiple states. Normally, an import
	// will map 1:1 to a physical resource. However, some resources map
	// to multiple. For example, an AWS security group may contain many rules.
	// Each rule is represented by a separate resource in OpenTofu,
	// therefore multiple states are returned.
	ImportState(*InstanceInfo, string) ([]*InstanceState, error)

	// ValidateDataSource is called once at the beginning with the raw
	// configuration (no interpolation done) and can return a list of warnings
	// and/or errors.
	//
	// This is called once per data source instance.
	//
	// This should not assume any of the values in the resource configuration
	// are valid since it is possible they have to be interpolated still.
	// The primary use case of this call is to check that the required keys
	// are set and that the general structure is correct.
	ValidateDataSource(string, *ResourceConfig) ([]string, []error)

	// DataSources returns all of the available data sources that this
	// provider implements.
	DataSources() []DataSource

	// ReadDataDiff produces a diff that represents the state that will
	// be produced when the given data source is read using a later call
	// to ReadDataApply.
	ReadDataDiff(*InstanceInfo, *ResourceConfig) (*InstanceDiff, error)

	// ReadDataApply initializes a data instance using the configuration
	// in a diff produced by ReadDataDiff.
	ReadDataApply(*InstanceInfo, *InstanceDiff) (*InstanceState, error)
}

ResourceProvider is a legacy interface for providers.

This is retained only for compatibility with legacy code. The current interface for providers is providers.Interface, in the sibling directory named "providers".

type ResourceProviderCloser

type ResourceProviderCloser interface {
	Close() error
}

ResourceProviderCloser is an interface that providers that can close connections that aren't needed anymore must implement.

type ResourceProviderFactory

type ResourceProviderFactory func() (ResourceProvider, error)

ResourceProviderFactory is a function type that creates a new instance of a resource provider.

func ResourceProviderFactoryFixed

func ResourceProviderFactoryFixed(p ResourceProvider) ResourceProviderFactory

ResourceProviderFactoryFixed is a helper that creates a ResourceProviderFactory that just returns some fixed provider.

type ResourceProvisioner

type ResourceProvisioner interface {
	// GetConfigSchema returns the schema for the provisioner type's main
	// configuration block. This is called prior to Validate to enable some
	// basic structural validation to be performed automatically and to allow
	// the configuration to be properly extracted from potentially-ambiguous
	// configuration file formats.
	GetConfigSchema() (*configschema.Block, error)

	// Validate is called once at the beginning with the raw
	// configuration (no interpolation done) and can return a list of warnings
	// and/or errors.
	//
	// This is called once per resource.
	//
	// This should not assume any of the values in the resource configuration
	// are valid since it is possible they have to be interpolated still.
	// The primary use case of this call is to check that the required keys
	// are set and that the general structure is correct.
	Validate(*ResourceConfig) ([]string, []error)

	// Apply runs the provisioner on a specific resource and returns an error.
	// Instead of a diff, the ResourceConfig is provided since provisioners
	// only run after a resource has been newly created.
	Apply(UIOutput, *InstanceState, *ResourceConfig) error

	// Stop is called when the provisioner should halt any in-flight actions.
	//
	// This can be used to make a nicer Ctrl-C experience for OpenTofu.
	// Even if this isn't implemented to do anything (just returns nil),
	// OpenTofu will still cleanly stop after the currently executing
	// graph node is complete. However, this API can be used to make more
	// efficient halts.
	//
	// Stop doesn't have to and shouldn't block waiting for in-flight actions
	// to complete. It should take any action it wants and return immediately
	// acknowledging it has received the stop request. OpenTofu core will
	// automatically not make any further API calls to the provider soon
	// after Stop is called (technically exactly once the currently executing
	// graph nodes are complete).
	//
	// The error returned, if non-nil, is assumed to mean that signaling the
	// stop somehow failed and that the user should expect potentially waiting
	// a longer period of time.
	Stop() error
}

ResourceProvisioner is an interface that must be implemented by any resource provisioner: the thing that initializes resources in a OpenTofu configuration.

type ResourceProvisionerCloser

type ResourceProvisionerCloser interface {
	Close() error
}

ResourceProvisionerCloser is an interface that provisioners that can close connections that aren't needed anymore must implement.

type ResourceProvisionerFactory

type ResourceProvisionerFactory func() (ResourceProvisioner, error)

ResourceProvisionerFactory is a function type that creates a new instance of a resource provisioner.

type ResourceState

type ResourceState struct {
	// This is filled in and managed by OpenTofu, and is the resource
	// type itself such as "mycloud_instance". If a resource provider sets
	// this value, it won't be persisted.
	Type string `json:"type"`

	// Dependencies are a list of things that this resource relies on
	// existing to remain intact. For example: an AWS instance might
	// depend on a subnet (which itself might depend on a VPC, and so
	// on).
	//
	// OpenTofu uses this information to build valid destruction
	// orders and to warn the user if they're destroying a resource that
	// another resource depends on.
	//
	// Things can be put into this list that may not be managed by
	// OpenTofu. If OpenTofu doesn't find a matching ID in the
	// overall state, then it assumes it isn't managed and doesn't
	// worry about it.
	Dependencies []string `json:"depends_on"`

	// Primary is the current active instance for this resource.
	// It can be replaced but only after a successful creation.
	// This is the instances on which providers will act.
	Primary *InstanceState `json:"primary"`

	// Deposed is used in the mechanics of CreateBeforeDestroy: the existing
	// Primary is Deposed to get it out of the way for the replacement Primary to
	// be created by Apply. If the replacement Primary creates successfully, the
	// Deposed instance is cleaned up.
	//
	// If there were problems creating the replacement Primary, the Deposed
	// instance and the (now tainted) replacement Primary will be swapped so the
	// tainted replacement will be cleaned up instead.
	//
	// An instance will remain in the Deposed list until it is successfully
	// destroyed and purged.
	Deposed []*InstanceState `json:"deposed"`

	// Provider is used when a resource is connected to a provider with an alias.
	// If this string is empty, the resource is connected to the default provider,
	// e.g. "aws_instance" goes with the "aws" provider.
	// If the resource block contained a "provider" key, that value will be set here.
	Provider string `json:"provider"`
	// contains filtered or unexported fields
}

ResourceState holds the state of a resource that is used so that a provider can find and manage an existing resource as well as for storing attributes that are used to populate variables of child resources.

Attributes has attributes about the created resource that are queryable in interpolation: "${type.id.attr}"

Extra is just extra data that a provider can return that we store for later, but is not exposed in any way to the user.

func (*ResourceState) Equal

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

Equal tests whether two ResourceStates are equal.

func (*ResourceState) Lock

func (s *ResourceState) Lock()

func (*ResourceState) ProviderAddr

func (s *ResourceState) ProviderAddr() (addrs.AbsProviderConfig, error)

ProviderAddr returns the provider address for the receiver, by parsing the string representation saved in state. An error can be returned if the value in state is corrupt.

func (*ResourceState) String

func (s *ResourceState) String() string

func (*ResourceState) Taint

func (s *ResourceState) Taint()

Taint marks a resource as tainted.

func (*ResourceState) Unlock

func (s *ResourceState) Unlock()

func (*ResourceState) Untaint

func (s *ResourceState) Untaint()

Untaint unmarks a resource as tainted.

type ResourceStateKey

type ResourceStateKey struct {
	Name  string
	Type  string
	Mode  ResourceMode
	Index int
}

ResourceStateKey is a structured representation of the key used for the ModuleState.Resources mapping

func ParseResourceStateKey

func ParseResourceStateKey(k string) (*ResourceStateKey, error)

ParseResourceStateKey accepts a key in the format used by ModuleState.Resources and returns a resource name and resource index. In the state, a resource has the format "type.name.index" or "type.name". In the latter case, the index is returned as -1.

func (*ResourceStateKey) Equal

func (rsk *ResourceStateKey) Equal(other *ResourceStateKey) bool

Equal determines whether two ResourceStateKeys are the same

func (*ResourceStateKey) String

func (rsk *ResourceStateKey) String() string

type ResourceType

type ResourceType struct {
	Name       string // Name of the resource, example "instance" (no provider prefix)
	Importable bool   // Whether this resource supports importing

	// SchemaAvailable is set if the provider supports the ProviderSchema,
	// ResourceTypeSchema and DataSourceSchema methods. Although it is
	// included on each resource type, it's actually a provider-wide setting
	// that's smuggled here only because that avoids a breaking change to
	// the plugin protocol.
	SchemaAvailable bool
}

ResourceType is a type of resource that a resource provider can manage.

type Schemas

type Schemas struct {
	Providers    map[addrs.Provider]*ProviderSchema
	Provisioners map[string]*configschema.Block
}

Schemas is a container for various kinds of schema that OpenTofu needs during processing.

func LoadSchemas

func LoadSchemas(config *configs.Config, state *states.State, components contextComponentFactory) (*Schemas, error)

LoadSchemas searches the given configuration, state and plan (any of which may be nil) for constructs that have an associated schema, requests the necessary schemas from the given component factory (which must _not_ be nil), and returns a single object representing all of the necessary schemas.

If an error is returned, it may be a wrapped tfdiags.Diagnostics describing errors across multiple separate objects. Errors here will usually indicate either misbehavior on the part of one of the providers or of the provider protocol itself. When returned with errors, the returned schemas object is still valid but may be incomplete.

func (*Schemas) ProviderConfig

func (ss *Schemas) ProviderConfig(provider addrs.Provider) *configschema.Block

ProviderConfig returns the schema for the provider configuration of the given provider type, or nil if no such schema is available.

func (*Schemas) ProviderSchema

func (ss *Schemas) ProviderSchema(provider addrs.Provider) *ProviderSchema

ProviderSchema returns the entire ProviderSchema object that was produced by the plugin for the given provider, or nil if no such schema is available.

It's usually better to go use the more precise methods offered by type Schemas to handle this detail automatically.

func (*Schemas) ProvisionerConfig

func (ss *Schemas) ProvisionerConfig(name string) *configschema.Block

ProvisionerConfig returns the schema for the configuration of a given provisioner, or nil of no such schema is available.

func (*Schemas) ResourceTypeConfig

func (ss *Schemas) ResourceTypeConfig(provider addrs.Provider, resourceMode addrs.ResourceMode, resourceType string) (block *configschema.Block, schemaVersion uint64)

ResourceTypeConfig returns the schema for the configuration of a given resource type belonging to a given provider type, or nil of no such schema is available.

In many cases the provider type is inferrable from the resource type name, but this is not always true because users can override the provider for a resource using the "provider" meta-argument. Therefore it's important to always pass the correct provider name, even though it many cases it feels redundant.

type Semaphore

type Semaphore chan struct{}

Semaphore is a wrapper around a channel to provide utility methods to clarify that we are treating the channel as a semaphore

func NewSemaphore

func NewSemaphore(n int) Semaphore

NewSemaphore creates a semaphore that allows up to a given limit of simultaneous acquisitions

func (Semaphore) Acquire

func (s Semaphore) Acquire()

Acquire is used to acquire an available slot. Blocks until available.

func (Semaphore) Release

func (s Semaphore) Release()

Release is used to return a slot. Acquire must be called as a pre-condition.

func (Semaphore) TryAcquire

func (s Semaphore) TryAcquire() bool

TryAcquire is used to do a non-blocking acquire. Returns a bool indicating success

type State

type State struct {
	// Version is the state file protocol version.
	Version int `json:"version"`

	// TFVersion is the version of OpenTofu that wrote this state.
	TFVersion string `json:"terraform_version,omitempty"`

	// Serial is incremented on any operation that modifies
	// the State file. It is used to detect potentially conflicting
	// updates.
	Serial int64 `json:"serial"`

	// Lineage is set when a new, blank state is created and then
	// never updated. This allows us to determine whether the serials
	// of two states can be meaningfully compared.
	// Apart from the guarantee that collisions between two lineages
	// are very unlikely, this value is opaque and external callers
	// should only compare lineage strings byte-for-byte for equality.
	Lineage string `json:"lineage"`

	// Remote is used to track the metadata required to
	// pull and push state files from a remote storage endpoint.
	Remote *RemoteState `json:"remote,omitempty"`

	// Backend tracks the configuration for the backend in use with
	// this state. This is used to track any changes in the backend
	// configuration.
	Backend *BackendState `json:"backend,omitempty"`

	// Modules contains all the modules in a breadth-first order
	Modules []*ModuleState `json:"modules"`
	// contains filtered or unexported fields
}

State keeps track of a snapshot state-of-the-world that OpenTofu can use to keep track of what real world resources it is actually managing.

func NewState

func NewState() *State

NewState is used to initialize a blank state

func ReadState

func ReadState(src io.Reader) (*State, error)

ReadState reads a state structure out of a reader in the format that was written by WriteState.

func ReadStateV2

func ReadStateV2(jsonBytes []byte) (*State, error)

func ReadStateV3

func ReadStateV3(jsonBytes []byte) (*State, error)

func (*State) AddModule

func (s *State) AddModule(path addrs.ModuleInstance) *ModuleState

AddModule adds the module with the given path to the state.

This should be the preferred method to add module states since it allows us to optimize lookups later as well as control sorting.

func (*State) AddModuleState

func (s *State) AddModuleState(mod *ModuleState)

AddModuleState insert this module state and override any existing ModuleState

func (*State) Children

func (s *State) Children(path []string) []*ModuleState

Children returns the ModuleStates that are direct children of the given path. If the path is "root", for example, then children returned might be "root.child", but not "root.child.grandchild".

func (*State) CompareAges

func (s *State) CompareAges(other *State) (StateAgeComparison, error)

CompareAges compares one state with another for which is "older".

This is a simple check using the state's serial, and is thus only as reliable as the serial itself. In the normal case, only one state exists for a given combination of lineage/serial, but OpenTofu does not guarantee this and so the result of this method should be used with care.

Returns an integer that is negative if the receiver is older than the argument, positive if the converse, and zero if they are equal. An error is returned if the two states are not of the same lineage, in which case the integer returned has no meaning.

func (*State) DeepCopy

func (s *State) DeepCopy() *State

DeepCopy performs a deep copy of the state structure and returns a new structure.

func (*State) Empty

func (s *State) Empty() bool

Empty returns true if the state is empty.

func (*State) EnsureHasLineage

func (s *State) EnsureHasLineage()

func (*State) Equal

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

Equal tests if one state is equal to another.

func (*State) FromFutureTofu

func (s *State) FromFutureTofu() bool

FromFutureTofu checks if this state was written by a OpenTofu version from the future.

func (*State) HasResources

func (s *State) HasResources() bool

HasResources returns true if the state contains any resources.

This is similar to !s.Empty, but returns true also in the case where the state has modules but all of them are devoid of resources.

func (*State) Init

func (s *State) Init()

func (*State) IsRemote

func (s *State) IsRemote() bool

IsRemote returns true if State represents a state that exists and is remote.

func (*State) Lock

func (s *State) Lock()

func (*State) MarshalEqual

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

MarshalEqual is similar to Equal but provides a stronger definition of "equal", where two states are equal if and only if their serialized form is byte-for-byte identical.

This is primarily useful for callers that are trying to save snapshots of state to persistent storage, allowing them to detect when a new snapshot must be taken.

Note that the serial number and lineage are included in the serialized form, so it's the caller's responsibility to properly manage these attributes so that this method is only called on two states that have the same serial and lineage, unless detecting such differences is desired.

func (*State) ModuleByPath

func (s *State) ModuleByPath(path addrs.ModuleInstance) *ModuleState

ModuleByPath is used to lookup the module state for the given path. This should be the preferred lookup mechanism as it allows for future lookup optimizations.

func (*State) Remove

func (s *State) Remove(addr ...string) error

Remove removes the item in the state at the given address, returning any errors that may have occurred.

If the address references a module state or resource, it will delete all children as well. To check what will be deleted, use a StateFilter first.

func (*State) RootModule

func (s *State) RootModule() *ModuleState

RootModule returns the ModuleState for the root module

func (*State) SameLineage

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

SameLineage returns true only if the state given in argument belongs to the same "lineage" of states as the receiver.

func (*State) String

func (s *State) String() string

func (*State) Unlock

func (s *State) Unlock()

func (*State) Validate

func (s *State) Validate() error

Validate validates the integrity of this state file.

Certain properties of the statefile are expected by OpenTofu in order to behave properly. The core of OpenTofu will assume that once it receives a State structure that it has been validated. This validation check should be called to ensure that.

If this returns an error, then the user should be notified. The error response will include detailed information on the nature of the error.

type StateAgeComparison

type StateAgeComparison int
const (
	StateAgeEqual         StateAgeComparison = 0
	StateAgeReceiverNewer StateAgeComparison = 1
	StateAgeReceiverOlder StateAgeComparison = -1
)

type StateFilter

type StateFilter struct {
	State *State
}

StateFilter is responsible for filtering and searching a state.

This is a separate struct from State rather than a method on State because StateFilter might create sidecar data structures to optimize filtering on the state.

If you change the State, the filter created is invalid and either Reset should be called or a new one should be allocated. StateFilter will not watch State for changes and do this for you. If you filter after changing the State without calling Reset, the behavior is not defined.

func (*StateFilter) Filter

func (f *StateFilter) Filter(fs ...string) ([]*StateFilterResult, error)

Filter takes the addresses specified by fs and finds all the matches. The values of fs are resource addressing syntax that can be parsed by ParseResourceAddress.

type StateFilterResult

type StateFilterResult struct {
	// Module path of the result
	Path []string

	// Address is the address that can be used to reference this exact result.
	Address string

	// Parent, if non-nil, is a parent of this result. For instances, the
	// parent would be a resource. For resources, the parent would be
	// a module. For modules, this is currently nil.
	Parent *StateFilterResult

	// Value is the actual value. This must be type switched on. It can be
	// any data structures that `State` can hold: `ModuleState`,
	// `ResourceState`, `InstanceState`.
	Value interface{}
}

StateFilterResult is a single result from a filter operation. Filter can match multiple things within a state (module, resource, instance, etc.) and this unifies that.

func (*StateFilterResult) String

func (r *StateFilterResult) String() string

type StateFilterResultSlice

type StateFilterResultSlice []*StateFilterResult

StateFilterResultSlice is a slice of results that implements sort.Interface. The sorting goal is what is most appealing to human output.

func (StateFilterResultSlice) Len

func (s StateFilterResultSlice) Len() int

func (StateFilterResultSlice) Less

func (s StateFilterResultSlice) Less(i, j int) bool

func (StateFilterResultSlice) Swap

func (s StateFilterResultSlice) Swap(i, j int)

type UIInput

type UIInput interface {
	Input(context.Context, *InputOpts) (string, error)
}

UIInput is the interface that must be implemented to ask for input from this user. This should forward the request to wherever the user inputs things to ask for values.

type UIOutput

type UIOutput interface {
	Output(string)
}

UIOutput is the interface that must be implemented to output data to the end user.

Jump to

Keyboard shortcuts

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