schema

package
v2.26.1 Latest Latest
Warning

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

Go to latest
Published: Mar 21, 2023 License: MPL-2.0 Imports: 36 Imported by: 4,770

README

Terraform Helper Lib: schema

The schema package provides a high-level interface for writing resource providers for Terraform.

If you're writing a resource provider, we recommend you use this package.

The interface exposed by this package is much friendlier than trying to write to the Terraform API directly. The core Terraform API is low-level and built for maximum flexibility and control, whereas this library is built as a framework around that to more easily write common providers.

Documentation

Overview

schema is a high-level framework for easily writing new providers for Terraform. Usage of schema is recommended over attempting to write to the low-level plugin interfaces manually.

schema breaks down provider creation into simple CRUD operations for resources. The logic of diffing, destroying before creating, updating or creating, etc. is all handled by the framework. The plugin author only needs to implement a configuration schema and the CRUD operations and everything else is meant to just work.

A good starting point is to view the Provider structure.

Index

Constants

View Source
const (
	// StringPlain indicates a string is plain-text and requires no processing for display.
	StringPlain = StringKind(configschema.StringPlain)

	// StringMarkdown indicates a string is in markdown format and may
	// require additional processing to display.
	StringMarkdown = StringKind(configschema.StringMarkdown)
)
View Source
const (
	TimeoutCreate  = "create"
	TimeoutRead    = "read"
	TimeoutUpdate  = "update"
	TimeoutDelete  = "delete"
	TimeoutDefault = "default"
)
View Source
const TimeoutKey = "e2bfb730-ecaa-11e6-8f88-34363bc7c4c0"
View Source
const TimeoutsConfigKey = "timeouts"

Variables

View Source
var (
	// DescriptionKind is the default StringKind of descriptions in this provider.
	// It defaults to StringPlain but can be globally switched to StringMarkdown.
	DescriptionKind = StringPlain

	// SchemaDescriptionBuilder converts helper/schema.Schema Descriptions to configschema.Attribute
	// and Block Descriptions. This method can be used to modify the description text prior to it
	// being returned in the schema.
	SchemaDescriptionBuilder = func(s *Schema) string {
		return s.Description
	}

	// ResourceDescriptionBuilder converts helper/schema.Resource Descriptions to configschema.Block
	// Descriptions at the resource top level. This method can be used to modify the description prior
	// to it being returned in the schema.
	ResourceDescriptionBuilder = func(r *Resource) string {
		return r.Description
	}
)
View Source
var ReservedDataSourceFields = []string{
	"connection",
	"count",
	"depends_on",
	"lifecycle",
	"provider",
	"provisioner",
}
View Source
var ReservedProviderFields = []string{
	"alias",
	"version",
}
View Source
var ReservedResourceFields = []string{
	"connection",
	"count",
	"depends_on",
	"lifecycle",
	"provider",
	"provisioner",
}
View Source
var (
	StopContextKey = Key("StopContext")
)

Functions

func ApplyDiff

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

ApplyDiff takes a cty.Value state and applies a terraform.InstanceDiff to get a new cty.Value state. This is used to convert the diff returned from the legacy provider Diff method to the state required for the new PlanResourceChange method.

func DefaultTimeout

func DefaultTimeout(tx interface{}) *time.Duration

could be time.Duration, int64 or float64

func DiffFromValues

func DiffFromValues(ctx context.Context, prior, planned, config cty.Value, res *Resource) (*terraform.InstanceDiff, error)

DiffFromValues takes the current state and desired state as cty.Values and derives a terraform.InstanceDiff to give to the legacy providers. This is used to take the states provided by the new ApplyResourceChange method and convert them to a state+diff required for the legacy Apply method.

func HashInt

func HashInt(v interface{}) int

HashInt hashes integers. If you want a Set of integers, this is the SchemaSetFunc you want.

func HashString

func HashString(v interface{}) int

HashString hashes strings. If you want a Set of strings, this is the SchemaSetFunc you want.

func JSONMapToStateValue

func JSONMapToStateValue(m map[string]interface{}, block *configschema.Block) (cty.Value, error)

JSONMapToStateValue takes a generic json map[string]interface{} and converts it to the specific type, ensuring that the values conform to the schema.

func Noop

func Noop(*ResourceData, interface{}) error

Noop is a convenience implementation of resource function which takes no action and returns no error.

func NoopContext

func NoopContext(context.Context, *ResourceData, interface{}) diag.Diagnostics

NoopContext is a convenience implementation of context aware resource function which takes no action and returns no error.

func RemoveFromState

func RemoveFromState(d *ResourceData, _ interface{}) error

RemoveFromState is a convenience implementation of a resource function which sets the resource ID to empty string (to remove it from state) and returns no error.

func SerializeResourceForHash

func SerializeResourceForHash(buf *bytes.Buffer, val interface{}, resource *Resource)

SerializeValueForHash appends a serialization of the given resource config to the given buffer, guaranteeing deterministic results given the same value and schema.

Its primary purpose is as input into a hashing function in order to hash complex substructures when used in sets, and so the serialization is not reversible.

func SerializeValueForHash

func SerializeValueForHash(buf *bytes.Buffer, val interface{}, schema *Schema)

func SetUnknowns added in v2.2.0

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

SetUnknowns takes a cty.Value, and compares it to the schema setting any null values which are computed to unknown.

func StateValueFromInstanceState

func StateValueFromInstanceState(is *terraform.InstanceState, ty cty.Type) (cty.Value, error)

StateValueFromInstanceState converts a terraform.InstanceState to a cty.Value as described by the provided cty.Type, and maintains the resource ID as the "id" attribute.

func StateValueToJSONMap

func StateValueToJSONMap(val cty.Value, ty cty.Type) (map[string]interface{}, error)

StateValueToJSONMap converts a cty.Value to generic JSON map via the cty JSON encoding.

func StopContext deprecated

func StopContext(ctx context.Context) (context.Context, bool)

StopContext returns a context safe for global use that will cancel when Terraform requests a stop. This function should only be called within a ConfigureContextFunc, passing in the request scoped context received in that method.

Deprecated: The use of a global context is discouraged. Please use the new context aware CRUD methods.

Types

type BasicMapReader

type BasicMapReader map[string]string

BasicMapReader implements MapReader for a single map.

func (BasicMapReader) Access

func (r BasicMapReader) Access(k string) (string, bool)

func (BasicMapReader) Range

func (r BasicMapReader) Range(f func(string, string) bool) bool

type ConfigFieldReader

type ConfigFieldReader struct {
	Config *terraform.ResourceConfig
	Schema map[string]*Schema
	// contains filtered or unexported fields
}

ConfigFieldReader reads fields out of an untyped map[string]string to the best of its ability. It also applies defaults from the Schema. (The other field readers do not need default handling because they source fully populated data structures.)

func (*ConfigFieldReader) ReadField

func (r *ConfigFieldReader) ReadField(address []string) (FieldReadResult, error)

type ConfigureContextFunc

type ConfigureContextFunc func(context.Context, *ResourceData) (interface{}, diag.Diagnostics)

ConfigureContextFunc is the function used to configure a Provider.

The interface{} value returned by this function is stored and passed into the subsequent resources as the meta parameter. This return value is usually used to pass along a configured API client, a configuration structure, etc.

type ConfigureFunc deprecated

type ConfigureFunc func(*ResourceData) (interface{}, error)

ConfigureFunc is the function used to configure a Provider.

Deprecated: Please use ConfigureContextFunc

type CreateContextFunc

type CreateContextFunc func(context.Context, *ResourceData, interface{}) diag.Diagnostics

See Resource documentation.

type CreateFunc deprecated

type CreateFunc func(*ResourceData, interface{}) error

The following function types are of the legacy CRUD operations.

Deprecated: Please use the context aware equivalents instead.

type CustomizeDiffFunc

type CustomizeDiffFunc func(context.Context, *ResourceDiff, interface{}) error

See Resource documentation.

type DeleteContextFunc

type DeleteContextFunc func(context.Context, *ResourceData, interface{}) diag.Diagnostics

See Resource documentation.

type DeleteFunc deprecated

type DeleteFunc func(*ResourceData, interface{}) error

Deprecated: Please use the context aware equivalents instead.

type DiffFieldReader

type DiffFieldReader struct {
	Diff   *terraform.InstanceDiff
	Source FieldReader
	Schema map[string]*Schema
	// contains filtered or unexported fields
}

DiffFieldReader reads fields out of a diff structures.

It also requires access to a Reader that reads fields from the structure that the diff was derived from. This is usually the state. This is required because a diff on its own doesn't have complete data about full objects such as maps.

The Source MUST be the data that the diff was derived from. If it isn't, the behavior of this struct is undefined.

Reading fields from a DiffFieldReader is identical to reading from Source except the diff will be applied to the end result.

The "Exists" field on the result will be set to true if the complete field exists whether its from the source, diff, or a combination of both. It cannot be determined whether a retrieved value is composed of diff elements.

func (*DiffFieldReader) ReadField

func (r *DiffFieldReader) ReadField(address []string) (FieldReadResult, error)

type Equal

type Equal interface {
	Equal(interface{}) bool
}

Equal is an interface that checks for deep equality between two objects.

type ExistsFunc deprecated

type ExistsFunc func(*ResourceData, interface{}) (bool, error)

Deprecated: Please use the context aware equivalents instead.

type FieldReadResult

type FieldReadResult struct {
	// Value is the actual read value. NegValue is the _negative_ value
	// or the items that should be removed (if they existed). NegValue
	// doesn't make sense for primitives but is important for any
	// container types such as maps, sets, lists.
	Value          interface{}
	ValueProcessed interface{}

	// Exists is true if the field was found in the data. False means
	// it wasn't found if there was no error.
	Exists bool

	// Computed is true if the field was found but the value
	// is computed.
	Computed bool
}

FieldReadResult encapsulates all the resulting data from reading a field.

func (*FieldReadResult) ValueOrZero

func (r *FieldReadResult) ValueOrZero(s *Schema) interface{}

ValueOrZero returns the value of this result or the zero value of the schema type, ensuring a consistent non-nil return value.

type FieldReader

type FieldReader interface {
	ReadField([]string) (FieldReadResult, error)
}

FieldReaders are responsible for decoding fields out of data into the proper typed representation. ResourceData uses this to query data out of multiple sources: config, state, diffs, etc.

type FieldWriter

type FieldWriter interface {
	WriteField([]string, interface{}) error
}

FieldWriters are responsible for writing fields by address into a proper typed representation. ResourceData uses this to write new data into existing sources.

type GRPCProviderServer added in v2.2.0

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

GRPCProviderServer handles the server, or plugin side of the rpc connection.

func NewGRPCProviderServer added in v2.2.0

func NewGRPCProviderServer(p *Provider) *GRPCProviderServer

func (*GRPCProviderServer) ApplyResourceChange added in v2.2.0

func (*GRPCProviderServer) ConfigureProvider added in v2.2.0

func (*GRPCProviderServer) GetProviderSchema added in v2.2.0

func (*GRPCProviderServer) ImportResourceState added in v2.2.0

func (*GRPCProviderServer) PlanResourceChange added in v2.2.0

func (*GRPCProviderServer) PrepareProviderConfig added in v2.2.0

func (*GRPCProviderServer) ReadDataSource added in v2.2.0

func (*GRPCProviderServer) ReadResource added in v2.2.0

func (*GRPCProviderServer) StopContext added in v2.2.0

func (s *GRPCProviderServer) StopContext(ctx context.Context) context.Context

StopContext derives a new context from the passed in grpc context. It creates a goroutine to wait for the server stop and propagates cancellation to the derived grpc context.

func (*GRPCProviderServer) StopProvider added in v2.2.0

func (*GRPCProviderServer) UpgradeResourceState added in v2.2.0

func (*GRPCProviderServer) ValidateDataSourceConfig added in v2.2.0

func (*GRPCProviderServer) ValidateResourceTypeConfig added in v2.2.0

type InternalMap

type InternalMap = schemaMap

InternalMap is used to aid in the transition to the new schema types and protocol. The name is not meant to convey any usefulness, as this is not to be used directly by any providers.

type Key added in v2.2.0

type Key string

type MapFieldReader

type MapFieldReader struct {
	Map    MapReader
	Schema map[string]*Schema
}

MapFieldReader reads fields out of an untyped map[string]string to the best of its ability.

func (*MapFieldReader) ReadField

func (r *MapFieldReader) ReadField(address []string) (FieldReadResult, error)

type MapFieldWriter

type MapFieldWriter struct {
	Schema map[string]*Schema
	// contains filtered or unexported fields
}

MapFieldWriter writes data into a single map[string]string structure.

func (*MapFieldWriter) Map

func (w *MapFieldWriter) Map() map[string]string

Map returns the underlying map that is being written to.

func (*MapFieldWriter) WriteField

func (w *MapFieldWriter) WriteField(addr []string, value interface{}) error

type MapReader

type MapReader interface {
	Access(string) (string, bool)
	Range(func(string, string) bool) bool
}

MapReader is an interface that is given to MapFieldReader for accessing a "map". This can be used to have alternate implementations. For a basic map[string]string, use BasicMapReader.

type MultiLevelFieldReader

type MultiLevelFieldReader struct {
	Readers map[string]FieldReader
	Levels  []string
}

MultiLevelFieldReader reads from other field readers, merging their results along the way in a specific order. You can specify "levels" and name them in order to read only an exact level or up to a specific level.

This is useful for saying things such as "read the field from the state and config and merge them" or "read the latest value of the field".

func (*MultiLevelFieldReader) ReadField

func (r *MultiLevelFieldReader) ReadField(address []string) (FieldReadResult, error)

func (*MultiLevelFieldReader) ReadFieldExact

func (r *MultiLevelFieldReader) ReadFieldExact(
	address []string, level string) (FieldReadResult, error)

func (*MultiLevelFieldReader) ReadFieldMerge

func (r *MultiLevelFieldReader) ReadFieldMerge(
	address []string, level string) (FieldReadResult, error)

type Provider

type Provider struct {
	// Schema is the schema for the configuration of this provider. If this
	// provider has no configuration, this can be omitted.
	//
	// The keys of this map are the configuration keys, and the value is
	// the schema describing the value of the configuration.
	Schema map[string]*Schema

	// ResourcesMap is the list of available resources that this provider
	// can manage, along with their Resource structure defining their
	// own schemas and CRUD operations.
	//
	// Provider automatically handles routing operations such as Apply,
	// Diff, etc. to the proper resource.
	ResourcesMap map[string]*Resource

	// DataSourcesMap is the collection of available data sources that
	// this provider implements, with a Resource instance defining
	// the schema and Read operation of each.
	//
	// Resource instances for data sources must have a Read function
	// and must *not* implement Create, Update or Delete.
	DataSourcesMap map[string]*Resource

	// ProviderMetaSchema is the schema for the configuration of the meta
	// information for this provider. If this provider has no meta info,
	// this can be omitted. This functionality is currently experimental
	// and subject to change or break without warning; it should only be
	// used by providers that are collaborating on its use with the
	// Terraform team.
	ProviderMetaSchema map[string]*Schema

	// ConfigureFunc is a function for configuring the provider. If the
	// provider doesn't need to be configured, this can be omitted.
	//
	// Deprecated: Please use ConfigureContextFunc instead.
	ConfigureFunc ConfigureFunc

	// ConfigureContextFunc is a function for configuring the provider. If the
	// provider doesn't need to be configured, this can be omitted. This function
	// receives a context.Context that will cancel when Terraform sends a
	// cancellation signal. This function can yield Diagnostics.
	ConfigureContextFunc ConfigureContextFunc

	TerraformVersion string
	// contains filtered or unexported fields
}

Provider represents a resource provider in Terraform, and properly implements all of the ResourceProvider API.

By defining a schema for the configuration of the provider, the map of supporting resources, and a configuration function, the schema framework takes over and handles all the provider operations for you.

After defining the provider structure, it is unlikely that you'll require any of the methods on Provider itself.

func (*Provider) Configure

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.

func (*Provider) DataSources

func (p *Provider) DataSources() []terraform.DataSource

DataSources returns all of the available data sources that this provider implements.

func (*Provider) GRPCProvider added in v2.2.0

func (p *Provider) GRPCProvider() tfprotov5.ProviderServer

GRPCProvider returns a gRPC server, for use with terraform-plugin-mux.

func (*Provider) GetSchema

GetSchema 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.

func (*Provider) ImportState

func (p *Provider) ImportState(
	ctx context.Context,
	info *terraform.InstanceInfo,
	id string) ([]*terraform.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 Terraform, therefore multiple states are returned.

func (*Provider) InternalValidate

func (p *Provider) InternalValidate() error

InternalValidate should be called to validate the structure of the provider.

This should be called in a unit test for any provider to verify before release that a provider is properly configured for use with this library.

func (*Provider) Meta

func (p *Provider) Meta() interface{}

Meta returns the metadata associated with this provider that was returned by the Configure call. It will be nil until Configure is called.

func (*Provider) Resources

func (p *Provider) Resources() []terraform.ResourceType

Resources returns all the available resource types that this provider knows how to manage.

func (*Provider) SetMeta

func (p *Provider) SetMeta(v interface{})

SetMeta can be used to forcefully set the Meta object of the provider. Note that if Configure is called the return value will override anything set here.

func (*Provider) UserAgent

func (p *Provider) UserAgent(name, version string) string

UserAgent returns a string suitable for use in the User-Agent header of requests generated by the provider. The generated string contains the version of Terraform, the Plugin SDK, and the provider used to generate the request. `name` should be the hyphen-separated reporting name of the provider, and `version` should be the version of the provider.

If TF_APPEND_USER_AGENT is set, its value will be appended to the returned string.

func (*Provider) Validate

Validate is called once at the beginning with the raw configuration (no interpolation done) and can return diagnostics

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.

func (*Provider) ValidateDataSource

func (p *Provider) ValidateDataSource(
	t string, c *terraform.ResourceConfig) diag.Diagnostics

ValidateDataSource is called once at the beginning with the raw configuration (no interpolation done) and can return diagnostics.

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.

func (*Provider) ValidateResource

func (p *Provider) ValidateResource(
	t string, c *terraform.ResourceConfig) diag.Diagnostics

ValidateResource is called once at the beginning with the raw configuration (no interpolation done) and can return diagnostics.

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.

type ReadContextFunc

type ReadContextFunc func(context.Context, *ResourceData, interface{}) diag.Diagnostics

See Resource documentation.

type ReadFunc deprecated

type ReadFunc func(*ResourceData, interface{}) error

Deprecated: Please use the context aware equivalents instead.

type Resource

type Resource struct {
	// Schema is the structure and type information for this component. This
	// field is required for all Resource concepts.
	//
	// The keys of this map are the names used in a practitioner configuration,
	// such as the attribute or block name. The values describe the structure
	// and type information of that attribute or block.
	Schema map[string]*Schema

	// SchemaVersion is the version number for this resource's Schema
	// definition. This field is only valid when the Resource is a managed
	// resource.
	//
	// The current SchemaVersion stored in the state for each resource.
	// Provider authors can increment this version number when Schema semantics
	// change in an incompatible manner. If the state's SchemaVersion is less
	// than the current SchemaVersion, the MigrateState and StateUpgraders
	// functionality is executed to upgrade the state information.
	//
	// When unset, SchemaVersion defaults to 0, so provider authors can start
	// their Versioning at any integer >= 1
	SchemaVersion int

	// MigrateState is responsible for updating an InstanceState with an old
	// version to the format expected by the current version of the Schema.
	// This field is only valid when the Resource is a managed resource.
	//
	// It is called during Refresh if the State's stored SchemaVersion is less
	// than the current SchemaVersion of the Resource.
	//
	// The function is yielded the state's stored SchemaVersion and a pointer to
	// the InstanceState that needs updating, as well as the configured
	// provider's configured meta interface{}, in case the migration process
	// needs to make any remote API calls.
	//
	// Deprecated: MigrateState is deprecated and any new changes to a resource's schema
	// should be handled by StateUpgraders. Existing MigrateState implementations
	// should remain for compatibility with existing state. MigrateState will
	// still be called if the stored SchemaVersion is less than the
	// first version of the StateUpgraders.
	MigrateState StateMigrateFunc

	// StateUpgraders contains the functions responsible for upgrading an
	// existing state with an old schema version to a newer schema. It is
	// called specifically by Terraform when the stored schema version is less
	// than the current SchemaVersion of the Resource. This field is only valid
	// when the Resource is a managed resource.
	//
	// StateUpgraders map specific schema versions to a StateUpgrader
	// function. The registered versions are expected to be ordered,
	// consecutive values. The initial value may be greater than 0 to account
	// for legacy schemas that weren't recorded and can be handled by
	// MigrateState.
	StateUpgraders []StateUpgrader

	// Create is called when the provider must create a new instance of a
	// managed resource. This field is only valid when the Resource is a
	// managed resource. Only one of Create, CreateContext, or
	// CreateWithoutTimeout should be implemented.
	//
	// The *ResourceData parameter contains the plan and state data for this
	// managed resource instance. The available data in the Get* methods is the
	// the proposed state, which is the merged data of the practitioner
	// configuration and any CustomizeDiff field logic.
	//
	// The SetId method must be called with a non-empty value for the managed
	// resource instance to be properly saved into the Terraform state and
	// avoid a "inconsistent result after apply" error.
	//
	// The interface{} parameter is the result of the Provider type
	// ConfigureFunc field execution. If the Provider does not define
	// a ConfigureFunc, this will be nil. This parameter is conventionally
	// used to store API clients and other provider instance specific data.
	//
	// The error return parameter, if not nil, will be converted into an error
	// diagnostic when passed back to Terraform.
	//
	// Deprecated: Use CreateContext or CreateWithoutTimeout instead. This
	// implementation does not support request cancellation initiated by
	// Terraform, such as a system or practitioner sending SIGINT (Ctrl-c).
	// This implementation also does not support warning diagnostics.
	Create CreateFunc

	// Read is called when the provider must refresh the state of a managed
	// resource instance or data resource instance. This field is only valid
	// when the Resource is a managed resource or data resource. Only one of
	// Read, ReadContext, or ReadWithoutTimeout should be implemented.
	//
	// The *ResourceData parameter contains the state data for this managed
	// resource instance or data resource instance.
	//
	// Managed resources can signal to Terraform that the managed resource
	// instance no longer exists and potentially should be recreated by calling
	// the SetId method with an empty string ("") parameter and without
	// returning an error.
	//
	// Data resources that are designed to return state for a singular
	// infrastructure component should conventionally return an error if that
	// infrastructure does not exist and omit any calls to the
	// SetId method.
	//
	// The interface{} parameter is the result of the Provider type
	// ConfigureFunc field execution. If the Provider does not define
	// a ConfigureFunc, this will be nil. This parameter is conventionally
	// used to store API clients and other provider instance specific data.
	//
	// The error return parameter, if not nil, will be converted into an error
	// diagnostic when passed back to Terraform.
	//
	// Deprecated: Use ReadContext or ReadWithoutTimeout instead. This
	// implementation does not support request cancellation initiated by
	// Terraform, such as a system or practitioner sending SIGINT (Ctrl-c).
	// This implementation also does not support warning diagnostics.
	Read ReadFunc

	// Update is called when the provider must update an instance of a
	// managed resource. This field is only valid when the Resource is a
	// managed resource. Only one of Update, UpdateContext, or
	// UpdateWithoutTimeout should be implemented.
	//
	// This implementation is optional. If omitted, all Schema must enable
	// the ForceNew field and any practitioner changes that would have
	// caused and update will instead destroy and recreate the infrastructure
	// compontent.
	//
	// The *ResourceData parameter contains the plan and state data for this
	// managed resource instance. The available data in the Get* methods is the
	// the proposed state, which is the merged data of the prior state,
	// practitioner configuration, and any CustomizeDiff field logic. The
	// available data for the GetChange* and HasChange* methods is the prior
	// state and proposed state.
	//
	// The interface{} parameter is the result of the Provider type
	// ConfigureFunc field execution. If the Provider does not define
	// a ConfigureFunc, this will be nil. This parameter is conventionally
	// used to store API clients and other provider instance specific data.
	//
	// The error return parameter, if not nil, will be converted into an error
	// diagnostic when passed back to Terraform.
	//
	// Deprecated: Use UpdateContext or UpdateWithoutTimeout instead. This
	// implementation does not support request cancellation initiated by
	// Terraform, such as a system or practitioner sending SIGINT (Ctrl-c).
	// This implementation also does not support warning diagnostics.
	Update UpdateFunc

	// Delete is called when the provider must destroy the instance of a
	// managed resource. This field is only valid when the Resource is a
	// managed resource. Only one of Delete, DeleteContext, or
	// DeleteWithoutTimeout should be implemented.
	//
	// The *ResourceData parameter contains the state data for this managed
	// resource instance.
	//
	// The interface{} parameter is the result of the Provider type
	// ConfigureFunc field execution. If the Provider does not define
	// a ConfigureFunc, this will be nil. This parameter is conventionally
	// used to store API clients and other provider instance specific data.
	//
	// The error return parameter, if not nil, will be converted into an error
	// diagnostic when passed back to Terraform.
	//
	// Deprecated: Use DeleteContext or DeleteWithoutTimeout instead. This
	// implementation does not support request cancellation initiated by
	// Terraform, such as a system or practitioner sending SIGINT (Ctrl-c).
	// This implementation also does not support warning diagnostics.
	Delete DeleteFunc

	// Exists is a function that is called to check if a resource still
	// exists. This field is only valid when the Resource is a managed
	// resource.
	//
	// If this returns false, then this will affect the diff
	// accordingly. If this function isn't set, it will not be called. You
	// can also signal existence in the Read method by calling d.SetId("")
	// if the Resource is no longer present and should be removed from state.
	// The *ResourceData passed to Exists should _not_ be modified.
	//
	// Deprecated: Remove in preference of ReadContext or ReadWithoutTimeout.
	Exists ExistsFunc

	// CreateContext is called when the provider must create a new instance of
	// a managed resource. This field is only valid when the Resource is a
	// managed resource. Only one of Create, CreateContext, or
	// CreateWithoutTimeout should be implemented.
	//
	// The Context parameter stores SDK information, such as loggers and
	// timeout deadlines. It also is wired to receive any cancellation from
	// Terraform such as a system or practitioner sending SIGINT (Ctrl-c).
	//
	// By default, CreateContext has a 20 minute timeout. Use the Timeouts
	// field to control the default duration or implement CreateWithoutTimeout
	// instead of CreateContext to remove the default timeout.
	//
	// The *ResourceData parameter contains the plan and state data for this
	// managed resource instance. The available data in the Get* methods is the
	// the proposed state, which is the merged data of the practitioner
	// configuration and any CustomizeDiff field logic.
	//
	// The SetId method must be called with a non-empty value for the managed
	// resource instance to be properly saved into the Terraform state and
	// avoid a "inconsistent result after apply" error.
	//
	// The interface{} parameter is the result of the Provider type
	// ConfigureFunc field execution. If the Provider does not define
	// a ConfigureFunc, this will be nil. This parameter is conventionally
	// used to store API clients and other provider instance specific data.
	//
	// The diagnostics return parameter, if not nil, can contain any
	// combination and multiple of warning and/or error diagnostics.
	CreateContext CreateContextFunc

	// ReadContext is called when the provider must refresh the state of a managed
	// resource instance or data resource instance. This field is only valid
	// when the Resource is a managed resource or data resource. Only one of
	// Read, ReadContext, or ReadWithoutTimeout should be implemented.
	//
	// The Context parameter stores SDK information, such as loggers and
	// timeout deadlines. It also is wired to receive any cancellation from
	// Terraform such as a system or practitioner sending SIGINT (Ctrl-c).
	//
	// By default, ReadContext has a 20 minute timeout. Use the Timeouts
	// field to control the default duration or implement ReadWithoutTimeout
	// instead of ReadContext to remove the default timeout.
	//
	// The *ResourceData parameter contains the state data for this managed
	// resource instance or data resource instance.
	//
	// Managed resources can signal to Terraform that the managed resource
	// instance no longer exists and potentially should be recreated by calling
	// the SetId method with an empty string ("") parameter and without
	// returning an error.
	//
	// Data resources that are designed to return state for a singular
	// infrastructure component should conventionally return an error if that
	// infrastructure does not exist and omit any calls to the
	// SetId method.
	//
	// The interface{} parameter is the result of the Provider type
	// ConfigureFunc field execution. If the Provider does not define
	// a ConfigureFunc, this will be nil. This parameter is conventionally
	// used to store API clients and other provider instance specific data.
	//
	// The diagnostics return parameter, if not nil, can contain any
	// combination and multiple of warning and/or error diagnostics.
	ReadContext ReadContextFunc

	// UpdateContext is called when the provider must update an instance of a
	// managed resource. This field is only valid when the Resource is a
	// managed resource. Only one of Update, UpdateContext, or
	// UpdateWithoutTimeout should be implemented.
	//
	// This implementation is optional. If omitted, all Schema must enable
	// the ForceNew field and any practitioner changes that would have
	// caused and update will instead destroy and recreate the infrastructure
	// compontent.
	//
	// The Context parameter stores SDK information, such as loggers and
	// timeout deadlines. It also is wired to receive any cancellation from
	// Terraform such as a system or practitioner sending SIGINT (Ctrl-c).
	//
	// By default, UpdateContext has a 20 minute timeout. Use the Timeouts
	// field to control the default duration or implement UpdateWithoutTimeout
	// instead of UpdateContext to remove the default timeout.
	//
	// The *ResourceData parameter contains the plan and state data for this
	// managed resource instance. The available data in the Get* methods is the
	// the proposed state, which is the merged data of the prior state,
	// practitioner configuration, and any CustomizeDiff field logic. The
	// available data for the GetChange* and HasChange* methods is the prior
	// state and proposed state.
	//
	// The interface{} parameter is the result of the Provider type
	// ConfigureFunc field execution. If the Provider does not define
	// a ConfigureFunc, this will be nil. This parameter is conventionally
	// used to store API clients and other provider instance specific data.
	//
	// The diagnostics return parameter, if not nil, can contain any
	// combination and multiple of warning and/or error diagnostics.
	UpdateContext UpdateContextFunc

	// DeleteContext is called when the provider must destroy the instance of a
	// managed resource. This field is only valid when the Resource is a
	// managed resource. Only one of Delete, DeleteContext, or
	// DeleteWithoutTimeout should be implemented.
	//
	// The Context parameter stores SDK information, such as loggers and
	// timeout deadlines. It also is wired to receive any cancellation from
	// Terraform such as a system or practitioner sending SIGINT (Ctrl-c).
	//
	// By default, DeleteContext has a 20 minute timeout. Use the Timeouts
	// field to control the default duration or implement DeleteWithoutTimeout
	// instead of DeleteContext to remove the default timeout.
	//
	// The *ResourceData parameter contains the state data for this managed
	// resource instance.
	//
	// The interface{} parameter is the result of the Provider type
	// ConfigureFunc field execution. If the Provider does not define
	// a ConfigureFunc, this will be nil. This parameter is conventionally
	// used to store API clients and other provider instance specific data.
	//
	// The diagnostics return parameter, if not nil, can contain any
	// combination and multiple of warning and/or error diagnostics.
	DeleteContext DeleteContextFunc

	// CreateWithoutTimeout is called when the provider must create a new
	// instance of a managed resource. This field is only valid when the
	// Resource is a managed resource. Only one of Create, CreateContext, or
	// CreateWithoutTimeout should be implemented.
	//
	// Most resources should prefer CreateContext with properly implemented
	// operation timeout values, however there are cases where operation
	// synchronization across concurrent resources is necessary in the resource
	// logic, such as a mutex, to prevent remote system errors. Since these
	// operations would have an indeterminate timeout that scales with the
	// number of resources, this allows resources to control timeout behavior.
	//
	// The Context parameter stores SDK information, such as loggers. It also
	// is wired to receive any cancellation from Terraform such as a system or
	// practitioner sending SIGINT (Ctrl-c).
	//
	// The *ResourceData parameter contains the plan and state data for this
	// managed resource instance. The available data in the Get* methods is the
	// the proposed state, which is the merged data of the practitioner
	// configuration and any CustomizeDiff field logic.
	//
	// The SetId method must be called with a non-empty value for the managed
	// resource instance to be properly saved into the Terraform state and
	// avoid a "inconsistent result after apply" error.
	//
	// The interface{} parameter is the result of the Provider type
	// ConfigureFunc field execution. If the Provider does not define
	// a ConfigureFunc, this will be nil. This parameter is conventionally
	// used to store API clients and other provider instance specific data.
	//
	// The diagnostics return parameter, if not nil, can contain any
	// combination and multiple of warning and/or error diagnostics.
	CreateWithoutTimeout CreateContextFunc

	// ReadWithoutTimeout is called when the provider must refresh the state of
	// a managed resource instance or data resource instance. This field is
	// only valid when the Resource is a managed resource or data resource.
	// Only one of Read, ReadContext, or ReadWithoutTimeout should be
	// implemented.
	//
	// Most resources should prefer ReadContext with properly implemented
	// operation timeout values, however there are cases where operation
	// synchronization across concurrent resources is necessary in the resource
	// logic, such as a mutex, to prevent remote system errors. Since these
	// operations would have an indeterminate timeout that scales with the
	// number of resources, this allows resources to control timeout behavior.
	//
	// The Context parameter stores SDK information, such as loggers. It also
	// is wired to receive any cancellation from Terraform such as a system or
	// practitioner sending SIGINT (Ctrl-c).
	//
	// The *ResourceData parameter contains the state data for this managed
	// resource instance or data resource instance.
	//
	// Managed resources can signal to Terraform that the managed resource
	// instance no longer exists and potentially should be recreated by calling
	// the SetId method with an empty string ("") parameter and without
	// returning an error.
	//
	// Data resources that are designed to return state for a singular
	// infrastructure component should conventionally return an error if that
	// infrastructure does not exist and omit any calls to the
	// SetId method.
	//
	// The interface{} parameter is the result of the Provider type
	// ConfigureFunc field execution. If the Provider does not define
	// a ConfigureFunc, this will be nil. This parameter is conventionally
	// used to store API clients and other provider instance specific data.
	//
	// The diagnostics return parameter, if not nil, can contain any
	// combination and multiple of warning and/or error diagnostics.
	ReadWithoutTimeout ReadContextFunc

	// UpdateWithoutTimeout is called when the provider must update an instance
	// of a managed resource. This field is only valid when the Resource is a
	// managed resource. Only one of Update, UpdateContext, or
	// UpdateWithoutTimeout should be implemented.
	//
	// Most resources should prefer UpdateContext with properly implemented
	// operation timeout values, however there are cases where operation
	// synchronization across concurrent resources is necessary in the resource
	// logic, such as a mutex, to prevent remote system errors. Since these
	// operations would have an indeterminate timeout that scales with the
	// number of resources, this allows resources to control timeout behavior.
	//
	// This implementation is optional. If omitted, all Schema must enable
	// the ForceNew field and any practitioner changes that would have
	// caused and update will instead destroy and recreate the infrastructure
	// compontent.
	//
	// The Context parameter stores SDK information, such as loggers. It also
	// is wired to receive any cancellation from Terraform such as a system or
	// practitioner sending SIGINT (Ctrl-c).
	//
	// The *ResourceData parameter contains the plan and state data for this
	// managed resource instance. The available data in the Get* methods is the
	// the proposed state, which is the merged data of the prior state,
	// practitioner configuration, and any CustomizeDiff field logic. The
	// available data for the GetChange* and HasChange* methods is the prior
	// state and proposed state.
	//
	// The interface{} parameter is the result of the Provider type
	// ConfigureFunc field execution. If the Provider does not define
	// a ConfigureFunc, this will be nil. This parameter is conventionally
	// used to store API clients and other provider instance specific data.
	//
	// The diagnostics return parameter, if not nil, can contain any
	// combination and multiple of warning and/or error diagnostics.
	UpdateWithoutTimeout UpdateContextFunc

	// DeleteWithoutTimeout is called when the provider must destroy the
	// instance of a managed resource. This field is only valid when the
	// Resource is a managed resource. Only one of Delete, DeleteContext, or
	// DeleteWithoutTimeout should be implemented.
	//
	// Most resources should prefer DeleteContext with properly implemented
	// operation timeout values, however there are cases where operation
	// synchronization across concurrent resources is necessary in the resource
	// logic, such as a mutex, to prevent remote system errors. Since these
	// operations would have an indeterminate timeout that scales with the
	// number of resources, this allows resources to control timeout behavior.
	//
	// The Context parameter stores SDK information, such as loggers. It also
	// is wired to receive any cancellation from Terraform such as a system or
	// practitioner sending SIGINT (Ctrl-c).
	//
	// The *ResourceData parameter contains the state data for this managed
	// resource instance.
	//
	// The interface{} parameter is the result of the Provider type
	// ConfigureFunc field execution. If the Provider does not define
	// a ConfigureFunc, this will be nil. This parameter is conventionally
	// used to store API clients and other provider instance specific data.
	//
	// The diagnostics return parameter, if not nil, can contain any
	// combination and multiple of warning and/or error diagnostics.
	DeleteWithoutTimeout DeleteContextFunc

	// CustomizeDiff is called after a difference (plan) has been generated
	// for the Resource and allows for customizations, such as setting values
	// not controlled by configuration, conditionally triggering resource
	// recreation, or implementing additional validation logic to abort a plan.
	// This field is only valid when the Resource is a managed resource.
	//
	// The Context parameter stores SDK information, such as loggers. It also
	// is wired to receive any cancellation from Terraform such as a system or
	// practitioner sending SIGINT (Ctrl-c).
	//
	// The *ResourceDiff parameter is similar to ResourceData but replaces the
	// Set method with other difference handling methods, such as SetNew,
	// SetNewComputed, and ForceNew. In general, only Schema with Computed
	// enabled can have those methods executed against them.
	//
	// The phases Terraform runs this in, and the state available via functions
	// like Get and GetChange, are as follows:
	//
	//  * New resource: One run with no state
	//  * Existing resource: One run with state
	//   * Existing resource, forced new: One run with state (before ForceNew),
	//     then one run without state (as if new resource)
	//  * Tainted resource: No runs (custom diff logic is skipped)
	//  * Destroy: No runs (standard diff logic is skipped on destroy diffs)
	//
	// This function needs to be resilient to support all scenarios.
	//
	// The interface{} parameter is the result of the Provider type
	// ConfigureFunc field execution. If the Provider does not define
	// a ConfigureFunc, this will be nil. This parameter is conventionally
	// used to store API clients and other provider instance specific data.
	//
	// The error return parameter, if not nil, will be converted into an error
	// diagnostic when passed back to Terraform.
	CustomizeDiff CustomizeDiffFunc

	// Importer is called when the provider must import an instance of a
	// managed resource. This field is only valid when the Resource is a
	// managed resource.
	//
	// If this is nil, then this resource does not support importing. If
	// this is non-nil, then it supports importing and ResourceImporter
	// must be validated. The validity of ResourceImporter is verified
	// by InternalValidate on Resource.
	Importer *ResourceImporter

	// If non-empty, this string is emitted as the details of a warning
	// diagnostic during validation (validate, plan, and apply operations).
	// This field is only valid when the Resource is a managed resource or
	// data resource.
	DeprecationMessage string

	// Timeouts configures the default time duration allowed before a create,
	// read, update, or delete operation is considered timed out, which returns
	// an error to practitioners. This field is only valid when the Resource is
	// a managed resource or data resource.
	//
	// When implemented, practitioners can add a timeouts configuration block
	// within their managed resource or data resource configuration to further
	// customize the create, read, update, or delete operation timeouts. For
	// example, a configuration may specify a longer create timeout for a
	// database resource due to its data size.
	//
	// The ResourceData that is passed to create, read, update, and delete
	// functionality can access the merged time duration of the Resource
	// default timeouts configured in this field and the practitioner timeouts
	// configuration via the Timeout method. Practitioner configuration
	// always overrides any default values set here, whether shorter or longer.
	Timeouts *ResourceTimeout

	// Description is used as the description for docs, the language server and
	// other user facing usage. It can be plain-text or markdown depending on the
	// global DescriptionKind setting. This field is valid for any Resource.
	Description string

	// UseJSONNumber should be set when state upgraders will expect
	// json.Numbers instead of float64s for numbers. This is added as a
	// toggle for backwards compatibility for type assertions, but should
	// be used in all new resources to avoid bugs with sufficiently large
	// user input. This field is only valid when the Resource is a managed
	// resource.
	//
	// See github.com/hashicorp/terraform-plugin-sdk/issues/655 for more
	// details.
	UseJSONNumber bool
}

Resource is an abstraction for multiple Terraform concepts:

  • Managed Resource: An infrastructure component with a schema, lifecycle operations such as create, read, update, and delete (CRUD), and optional implementation details such as import support, upgrade state support, and difference customization.
  • Data Resource: Also known as a data source. An infrastructure component with a schema and only the read lifecycle operation.
  • Block: When implemented within a Schema type Elem field, a configuration block that contains nested schema information such as attributes and blocks.

To fully implement managed resources, the Provider type ResourcesMap field should include a reference to an implementation of this type. To fully implement data resources, the Provider type DataSourcesMap field should include a reference to an implementation of this type.

Each field further documents any constraints based on the Terraform concept being implemented.

func DataSourceResourceShim

func DataSourceResourceShim(name string, dataSource *Resource) *Resource

DataSourceResourceShim takes a Resource instance describing a data source (with a Read implementation and a Schema, at least) and returns a new Resource instance with additional Create and Delete implementations that allow the data source to be used as a resource.

This is a backward-compatibility layer for data sources that were formerly read-only resources before the data source concept was added. It should not be used for any *new* data sources.

The Read function for the data source *must* call d.SetId with a non-empty id in order for this shim to function as expected.

The provided Resource instance, and its schema, will be modified in-place to make it suitable for use as a full resource.

func (*Resource) Apply

Apply creates, updates, and/or deletes a resource.

func (*Resource) CoreConfigSchema

func (r *Resource) CoreConfigSchema() *configschema.Block

CoreConfigSchema is a convenient shortcut for calling CoreConfigSchema on the resource's schema. CoreConfigSchema adds the implicitly required "id" attribute for top level resources if it doesn't exist.

func (*Resource) Data

Data returns a ResourceData struct for this Resource. Each return value is a separate copy and can be safely modified differently.

The data returned from this function has no actual affect on the Resource itself (including the state given to this function).

This function is useful for unit tests and ResourceImporter functions.

func (*Resource) Diff

func (r *Resource) Diff(
	ctx context.Context,
	s *terraform.InstanceState,
	c *terraform.ResourceConfig,
	meta interface{}) (*terraform.InstanceDiff, error)

Diff returns a diff of this resource.

func (*Resource) InternalValidate

func (r *Resource) InternalValidate(topSchemaMap schemaMap, writable bool) error

InternalValidate should be called to validate the structure of the resource.

This should be called in a unit test for any resource to verify before release that a resource is properly configured for use with this library.

Provider.InternalValidate() will automatically call this for all of the resources it manages, so you don't need to call this manually if it is part of a Provider.

func (*Resource) ReadDataApply

func (r *Resource) ReadDataApply(
	ctx context.Context,
	d *terraform.InstanceDiff,
	meta interface{},
) (*terraform.InstanceState, diag.Diagnostics)

ReadDataApply loads the data for a data source, given a diff that describes the configuration arguments and desired computed attributes.

func (*Resource) RefreshWithoutUpgrade

func (r *Resource) RefreshWithoutUpgrade(
	ctx context.Context,
	s *terraform.InstanceState,
	meta interface{}) (*terraform.InstanceState, diag.Diagnostics)

RefreshWithoutUpgrade reads the instance state, but does not call MigrateState or the StateUpgraders, since those are now invoked in a separate API call. RefreshWithoutUpgrade is part of the new plugin shims.

func (*Resource) ShimInstanceStateFromValue

func (r *Resource) ShimInstanceStateFromValue(state cty.Value) (*terraform.InstanceState, error)

ShimInstanceStateFromValue converts a cty.Value to a terraform.InstanceState.

func (*Resource) SimpleDiff

func (r *Resource) SimpleDiff(
	ctx context.Context,
	s *terraform.InstanceState,
	c *terraform.ResourceConfig,
	meta interface{}) (*terraform.InstanceDiff, error)

func (*Resource) TestResourceData

func (r *Resource) TestResourceData() *ResourceData

TestResourceData Yields a ResourceData filled with this resource's schema for use in unit testing

TODO: May be able to be removed with the above ResourceData function.

func (*Resource) Validate

Validate validates the resource configuration against the schema.

type ResourceData

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

ResourceData is used to query and set the attributes of a resource.

ResourceData is the primary argument received for CRUD operations on a resource as well as configuration of a provider. It is a powerful structure that can be used to not only query data, but also check for changes

The most relevant methods to take a look at are Get and Set.

func ImportStatePassthrough deprecated

func ImportStatePassthrough(d *ResourceData, m interface{}) ([]*ResourceData, error)

ImportStatePassthrough is an implementation of StateFunc that can be used to simply pass the ID directly through.

Deprecated: Please use the context aware ImportStatePassthroughContext instead

func ImportStatePassthroughContext

func ImportStatePassthroughContext(ctx context.Context, d *ResourceData, m interface{}) ([]*ResourceData, error)

ImportStatePassthroughContext is an implementation of StateContextFunc that can be used to simply pass the ID directly through. This should be used only in the case that an ID-only refresh is possible.

func TestResourceDataRaw

func TestResourceDataRaw(t testing.T, schema map[string]*Schema, raw map[string]interface{}) *ResourceData

TestResourceDataRaw creates a ResourceData from a raw configuration map.

func (*ResourceData) ConnInfo

func (d *ResourceData) ConnInfo() map[string]string

ConnInfo returns the connection info for this resource.

func (*ResourceData) Get

func (d *ResourceData) Get(key string) interface{}

Get returns the data for the given key, or nil if the key doesn't exist in the schema.

If the key does exist in the schema but doesn't exist in the configuration, then the default value for that type will be returned. For strings, this is "", for numbers it is 0, etc.

If you want to test if something is set at all in the configuration, use GetOk.

func (*ResourceData) GetChange

func (d *ResourceData) GetChange(key string) (interface{}, interface{})

GetChange returns the old and new value for a given key.

HasChange should be used to check if a change exists. It is possible that both the old and new value are the same if the old value was not set and the new value is. This is common, for example, for boolean fields which have a zero value of false.

func (*ResourceData) GetOk

func (d *ResourceData) GetOk(key string) (interface{}, bool)

GetOk returns the data for the given key and whether or not the key has been set to a non-zero value at some point.

The first result will not necessarilly be nil if the value doesn't exist. The second result should be checked to determine this information.

func (*ResourceData) GetOkExists deprecated

func (d *ResourceData) GetOkExists(key string) (interface{}, bool)

GetOkExists can check if TypeBool attributes that are Optional with no Default value have been set.

Deprecated: usage is discouraged due to undefined behaviors and may be removed in a future version of the SDK

func (*ResourceData) GetProviderMeta

func (d *ResourceData) GetProviderMeta(dst interface{}) error

func (*ResourceData) GetRawConfig added in v2.8.0

func (d *ResourceData) GetRawConfig() cty.Value

GetRawConfig returns the cty.Value that Terraform sent the SDK for the config. If no value was sent, or if a null value was sent, the value will be a null value of the resource's type.

GetRawConfig is considered experimental and advanced functionality, and familiarity with the Terraform protocol is suggested when using it.

func (*ResourceData) GetRawPlan added in v2.8.0

func (d *ResourceData) GetRawPlan() cty.Value

GetRawPlan returns the cty.Value that Terraform sent the SDK for the plan. If no value was sent, or if a null value was sent, the value will be a null value of the resource's type.

GetRawPlan is considered experimental and advanced functionality, and familiarity with the Terraform protocol is suggested when using it.

func (*ResourceData) GetRawState added in v2.8.0

func (d *ResourceData) GetRawState() cty.Value

GetRawState returns the cty.Value that Terraform sent the SDK for the state. If no value was sent, or if a null value was sent, the value will be a null value of the resource's type.

GetRawState is considered experimental and advanced functionality, and familiarity with the Terraform protocol is suggested when using it.

func (*ResourceData) HasChange

func (d *ResourceData) HasChange(key string) bool

HasChange returns whether or not the given key has been changed.

func (*ResourceData) HasChangeExcept added in v2.3.0

func (d *ResourceData) HasChangeExcept(key string) bool

HasChangeExcept returns whether any keys outside the given key have been changed.

This function only works with root attribute keys.

func (*ResourceData) HasChanges

func (d *ResourceData) HasChanges(keys ...string) bool

HasChanges returns whether or not any of the given keys has been changed.

func (*ResourceData) HasChangesExcept added in v2.3.0

func (d *ResourceData) HasChangesExcept(keys ...string) bool

HasChangesExcept returns whether any keys outside the given keys have been changed.

This function only works with root attribute keys.

func (*ResourceData) Id

func (d *ResourceData) Id() string

Id returns the ID of the resource.

func (*ResourceData) IsNewResource

func (d *ResourceData) IsNewResource() bool

func (*ResourceData) MarkNewResource

func (d *ResourceData) MarkNewResource()

func (*ResourceData) Partial

func (d *ResourceData) Partial(on bool)

Partial is a legacy function that was used for capturing state of specific attributes if an update only partially worked. Enabling this flag without setting any specific keys with the now removed SetPartial has a useful side effect of preserving all of the resource's previous state. Although confusing, it has been discovered that during an update when an error is returned, the proposed config is set into state, even without any calls to d.Set.

In practice this default behavior goes mostly unnoticed since Terraform refreshes between operations by default. The state situation discussed is subject to further investigation and potential change. Until then, this function has been preserved for the specific usecase.

func (*ResourceData) Set

func (d *ResourceData) Set(key string, value interface{}) error

Set sets the value for the given key.

If the key is invalid or the value is not a correct type, an error will be returned.

func (*ResourceData) SetConnInfo

func (d *ResourceData) SetConnInfo(v map[string]string)

SetConnInfo sets the connection info for a resource.

func (*ResourceData) SetId

func (d *ResourceData) SetId(v string)

SetId sets the ID of the resource. If the value is blank, then the resource is destroyed.

func (*ResourceData) SetType

func (d *ResourceData) SetType(t string)

SetType sets the ephemeral type for the data. This is only required for importing.

func (*ResourceData) State

func (d *ResourceData) State() *terraform.InstanceState

State returns the new InstanceState after the diff and any Set calls.

func (*ResourceData) Timeout

func (d *ResourceData) Timeout(key string) time.Duration

Timeout returns the data for the given timeout key Returns a duration of 20 minutes for any key not found, or not found and no default.

type ResourceDiff

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

ResourceDiff is used to query and make custom changes to an in-flight diff. It can be used to veto particular changes in the diff, customize the diff that has been created, or diff values not controlled by config.

The object functions similar to ResourceData, however most notably lacks Set, SetPartial, and Partial, as it should be used to change diff values only. Most other first-class ResourceData functions exist, namely Get, GetOk, HasChange, and GetChange exist.

All functions in ResourceDiff, save for ForceNew, can only be used on computed fields.

func (*ResourceDiff) Clear

func (d *ResourceDiff) Clear(key string) error

Clear wipes the diff for a particular key. It is called by ResourceDiff's functionality to remove any possibility of conflicts, but can be called on its own to just remove a specific key from the diff completely.

Note that this does not wipe an override. This function is only allowed on computed keys.

func (*ResourceDiff) ForceNew

func (d *ResourceDiff) ForceNew(key string) error

ForceNew force-flags ForceNew in the schema for a specific key, and re-calculates its diff, effectively causing this attribute to force a new resource.

Keep in mind that forcing a new resource will force a second run of the resource's CustomizeDiff function (with a new ResourceDiff) once the current one has completed. This second run is performed without state. This behavior will be the same as if a new resource is being created and is performed to ensure that the diff looks like the diff for a new resource as much as possible. CustomizeDiff should expect such a scenario and act correctly.

This function is a no-op/error if there is no diff.

Note that the change to schema is permanent for the lifecycle of this specific ResourceDiff instance.

func (*ResourceDiff) Get

func (d *ResourceDiff) Get(key string) interface{}

Get hands off to ResourceData.Get.

func (*ResourceDiff) GetChange

func (d *ResourceDiff) GetChange(key string) (interface{}, interface{})

GetChange gets the change between the state and diff, checking first to see if an overridden diff exists.

This implementation differs from ResourceData's in the way that we first get results from the exact levels for the new diff, then from state and diff as per normal.

func (*ResourceDiff) GetChangedKeysPrefix

func (d *ResourceDiff) GetChangedKeysPrefix(prefix string) []string

GetChangedKeysPrefix helps to implement Resource.CustomizeDiff where we need to act on all nested fields without calling out each one separately. An empty prefix is supported, returning all changed keys.

func (*ResourceDiff) GetOk

func (d *ResourceDiff) GetOk(key string) (interface{}, bool)

GetOk functions the same way as ResourceData.GetOk, but it also checks the new diff levels to provide data consistent with the current state of the customized diff.

func (*ResourceDiff) GetOkExists

func (d *ResourceDiff) GetOkExists(key string) (interface{}, bool)

GetOkExists functions the same way as GetOkExists within ResourceData, but it also checks the new diff levels to provide data consistent with the current state of the customized diff.

This is nearly the same function as GetOk, yet it does not check for the zero value of the attribute's type. This allows for attributes without a default, to fully check for a literal assignment, regardless of the zero-value for that type.

func (*ResourceDiff) GetRawConfig added in v2.8.0

func (d *ResourceDiff) GetRawConfig() cty.Value

GetRawConfig returns the cty.Value that Terraform sent the SDK for the config. If no value was sent, or if a null value was sent, the value will be a null value of the resource's type.

GetRawConfig is considered experimental and advanced functionality, and familiarity with the Terraform protocol is suggested when using it.

func (*ResourceDiff) GetRawPlan added in v2.8.0

func (d *ResourceDiff) GetRawPlan() cty.Value

GetRawPlan returns the cty.Value that Terraform sent the SDK for the plan. If no value was sent, or if a null value was sent, the value will be a null value of the resource's type.

GetRawPlan is considered experimental and advanced functionality, and familiarity with the Terraform protocol is suggested when using it.

func (*ResourceDiff) GetRawState added in v2.8.0

func (d *ResourceDiff) GetRawState() cty.Value

GetRawState returns the cty.Value that Terraform sent the SDK for the state. If no value was sent, or if a null value was sent, the value will be a null value of the resource's type.

GetRawState is considered experimental and advanced functionality, and familiarity with the Terraform protocol is suggested when using it.

func (*ResourceDiff) HasChange

func (d *ResourceDiff) HasChange(key string) bool

HasChange checks to see if there is a change between state and the diff, or in the overridden diff.

func (*ResourceDiff) HasChanges added in v2.11.0

func (d *ResourceDiff) HasChanges(keys ...string) bool

HasChanges returns whether or not any of the given keys has been changed.

func (*ResourceDiff) Id

func (d *ResourceDiff) Id() string

Id returns the ID of this resource.

Note that technically, ID does not change during diffs (it either has already changed in the refresh, or will change on update), hence we do not support updating the ID or fetching it from anything else other than state.

func (*ResourceDiff) NewValueKnown

func (d *ResourceDiff) NewValueKnown(key string) bool

NewValueKnown returns true if the new value for the given key is available as its final value at diff time. If the return value is false, this means either the value is based of interpolation that was unavailable at diff time, or that the value was explicitly marked as computed by SetNewComputed.

func (*ResourceDiff) SetNew

func (d *ResourceDiff) SetNew(key string, value interface{}) error

SetNew is used to set a new diff value for the mentioned key. The value must be correct for the attribute's schema (mostly relevant for maps, lists, and sets). The original value from the state is used as the old value.

This function is only allowed on computed attributes.

func (*ResourceDiff) SetNewComputed

func (d *ResourceDiff) SetNewComputed(key string) error

SetNewComputed functions like SetNew, except that it blanks out a new value and marks it as computed.

This function is only allowed on computed attributes.

func (*ResourceDiff) UpdatedKeys

func (d *ResourceDiff) UpdatedKeys() []string

UpdatedKeys returns the keys that were updated by this ResourceDiff run. These are the only keys that a diff should be re-calculated for.

This is the combined result of both keys for which diff values were updated for or cleared, and also keys that were flagged to be re-diffed as a result of ForceNew.

type ResourceImporter

type ResourceImporter struct {
	// State is called to convert an ID to one or more InstanceState to
	// insert into the Terraform state.
	//
	// Deprecated: State is deprecated in favor of StateContext.
	// Only one of the two functions can bet set.
	State StateFunc

	// StateContext is called to convert an ID to one or more InstanceState to
	// insert into the Terraform state. If this isn't specified, then
	// the ID is passed straight through. This function receives a context
	// that will cancel if Terraform sends a cancellation signal.
	StateContext StateContextFunc
}

ResourceImporter defines how a resource is imported in Terraform. This can be set onto a Resource struct to make it Importable. Not all resources have to be importable; if a Resource doesn't have a ResourceImporter then it won't be importable.

"Importing" in Terraform is the process of taking an already-created resource and bringing it under Terraform management. This can include updating Terraform state, generating Terraform configuration, etc.

func (*ResourceImporter) InternalValidate

func (r *ResourceImporter) InternalValidate() error

InternalValidate should be called to validate the structure of this importer. This should be called in a unit test.

Resource.InternalValidate() will automatically call this, so this doesn't need to be called manually. Further, Resource.InternalValidate() is automatically called by Provider.InternalValidate(), so you only need to internal validate the provider.

type ResourceTimeout

type ResourceTimeout struct {
	Create, Read, Update, Delete, Default *time.Duration
}

func (*ResourceTimeout) ConfigDecode

func (t *ResourceTimeout) ConfigDecode(s *Resource, c *terraform.ResourceConfig) error

ConfigDecode takes a schema and the configuration (available in Diff) and validates, parses the timeouts into `t`

func (*ResourceTimeout) DiffDecode

func (t *ResourceTimeout) DiffDecode(is *terraform.InstanceDiff) error

func (*ResourceTimeout) DiffEncode

func (t *ResourceTimeout) DiffEncode(id *terraform.InstanceDiff) error

DiffEncode, StateEncode, and MetaDecode are analogous to the Go stdlib JSONEncoder interface: they encode/decode a timeouts struct from an instance diff, which is where the timeout data is stored after a diff to pass into Apply.

StateEncode encodes the timeout into the ResourceData's InstanceState for saving to state

func (*ResourceTimeout) StateDecode

func (t *ResourceTimeout) StateDecode(id *terraform.InstanceState) error

func (*ResourceTimeout) StateEncode

func (t *ResourceTimeout) StateEncode(is *terraform.InstanceState) error

type Schema

type Schema struct {
	// Type is the type of the value and must be one of the ValueType values.
	//
	// This type not only determines what type is expected/valid in configuring
	// this value, but also what type is returned when ResourceData.Get is
	// called. The types returned by Get are:
	//
	//   TypeBool - bool
	//   TypeInt - int
	//   TypeFloat - float64
	//   TypeString - string
	//   TypeList - []interface{}
	//   TypeMap - map[string]interface{}
	//   TypeSet - *schema.Set
	//
	Type ValueType

	// ConfigMode allows for overriding the default behaviors for mapping
	// schema entries onto configuration constructs.
	//
	// By default, the Elem field is used to choose whether a particular
	// schema is represented in configuration as an attribute or as a nested
	// block; if Elem is a *schema.Resource then it's a block and it's an
	// attribute otherwise.
	//
	// If Elem is *schema.Resource then setting ConfigMode to
	// SchemaConfigModeAttr will force it to be represented in configuration
	// as an attribute, which means that the Computed flag can be used to
	// provide default elements when the argument isn't set at all, while still
	// allowing the user to force zero elements by explicitly assigning an
	// empty list.
	//
	// When Computed is set without Optional, the attribute is not settable
	// in configuration at all and so SchemaConfigModeAttr is the automatic
	// behavior, and SchemaConfigModeBlock is not permitted.
	ConfigMode SchemaConfigMode

	// Required indicates whether the practitioner must enter a value in the
	// configuration for this attribute. Required cannot be used with Computed
	// Default, DefaultFunc, DiffSuppressFunc, DiffSuppressOnRefresh,
	// InputDefault, Optional, or StateFunc. At least one of Required,
	// Optional, Optional and Computed, or Computed must be enabled.
	Required bool

	// Optional indicates whether the practitioner can choose to not enter
	// a value in the configuration for this attribute. Optional cannot be used
	// with Required.
	//
	// If also using Default or DefaultFunc, Computed should also be enabled,
	// otherwise Terraform can output warning logs or "inconsistent result
	// after apply" errors.
	Optional bool

	// Computed indicates whether the provider may return its own value for
	// this attribute or not. Computed cannot be used with Required. If
	// Required and Optional are both false, the attribute will be considered
	// "read only" for the practitioner, with only the provider able to set
	// its value.
	Computed bool

	// ForceNew indicates whether a change in this value requires the
	// replacement (destroy and create) of the managed resource instance,
	// rather than an in-place update. This field is only valid when the
	// encapsulating Resource is a managed resource.
	//
	// If conditional replacement logic is needed, use the Resource type
	// CustomizeDiff field to call the ResourceDiff type ForceNew method.
	ForceNew bool

	// If this is non-nil, the provided function will be used during diff
	// of this field. If this is nil, a default diff for the type of the
	// schema will be used.
	//
	// This allows comparison based on something other than primitive, list
	// or map equality - for example SSH public keys may be considered
	// equivalent regardless of trailing whitespace.
	//
	// If CustomizeDiffFunc makes this field ForceNew=true, the
	// following DiffSuppressFunc will come in with the value of old being
	// empty, as if creating a new resource.
	//
	// By default, DiffSuppressFunc is considered only when deciding whether
	// a configuration value is significantly different than the prior state
	// value during planning. Set DiffSuppressOnRefresh to opt in to checking
	// this also during the refresh step.
	DiffSuppressFunc SchemaDiffSuppressFunc

	// DiffSuppressOnRefresh enables using the DiffSuppressFunc to ignore
	// normalization-classified changes returned by the resource type's
	// "Read" or "ReadContext" function, in addition to the default behavior of
	// doing so during planning.
	//
	// This is a particularly good choice for attributes which take strings
	// containing "microsyntaxes" where various different values are packed
	// together in some serialization where there are many ways to express the
	// same information. For example, attributes which accept JSON data can
	// include different whitespace characters without changing meaning, and
	// case-insensitive identifiers may refer to the same object using different
	// characters.
	//
	// This is valid only for attributes of primitive types, because
	// DiffSuppressFunc itself is only compatible with primitive types.
	//
	// The key benefit of activating this flag is that the result of Read or
	// ReadContext will be cleaned of normalization-only changes in the same
	// way as the planning result would normaly be, which therefore prevents
	// churn for downstream expressions deriving from this attribute and
	// prevents incorrect "Values changed outside of Terraform" messages
	// when the remote API returns values which have the same meaning as the
	// prior state but in a different serialization.
	//
	// This is an opt-in because it was a later addition to the DiffSuppressFunc
	// functionality which would cause some significant changes in behavior
	// for existing providers if activated everywhere all at once.
	DiffSuppressOnRefresh bool

	// Default indicates a value to set if this attribute is not set in the
	// configuration. Default cannot be used with DefaultFunc or Required.
	// Default is only supported if the Type is TypeBool, TypeFloat, TypeInt,
	// or TypeString. Default cannot be used if the Schema is directly an
	// implementation of an Elem field of another Schema, such as trying to
	// set a default value for a TypeList or TypeSet.
	//
	// Changing either Default can be a breaking change, especially if the
	// attribute has ForceNew enabled. If a default needs to change to align
	// with changing assumptions in an upstream API, then it may be necessary
	// to also implement resource state upgrade functionality to change the
	// state to match or update read operation logic to align with the new
	// default.
	Default interface{}

	// DefaultFunc can be specified to compute a dynamic default when this
	// attribute is not set in the configuration. DefaultFunc cannot be used
	// with Default. For legacy reasons, DefaultFunc can be used with Required
	// attributes in a Provider schema, which will prompt practitioners for
	// input if the result of this function is nil.
	//
	// The return value should be stable to avoid generating confusing
	// plan differences. Changing the return value can be a breaking change,
	// especially if ForceNew is enabled. If a default needs to change to align
	// with changing assumptions in an upstream API, then it may be necessary
	// to also implement resource state upgrade functionality to change the
	// state to match or update read operation logic to align with the new
	// default.
	DefaultFunc SchemaDefaultFunc

	// Description is used as the description for docs, the language server and
	// other user facing usage. It can be plain-text or markdown depending on the
	// global DescriptionKind setting.
	Description string

	// InputDefault is the default value to use for when inputs are requested.
	// This differs from Default in that if Default is set, no input is
	// asked for. If Input is asked, this will be the default value offered.
	InputDefault string

	// StateFunc is a function called to change the value of this before
	// storing it in the state (and likewise before comparing for diffs).
	// The use for this is for example with large strings, you may want
	// to simply store the hash of it.
	StateFunc SchemaStateFunc

	// Elem represents the element type for a TypeList, TypeSet, or TypeMap
	// attribute or block. The only valid types are *Schema and *Resource.
	// Only TypeList and TypeSet support *Resource.
	//
	// If the Elem is a *Schema, the surrounding Schema represents a single
	// attribute with a single element type for underlying elements. In
	// practitioner configurations, an equals sign (=) is required to set
	// the value. Refer to the following documentation:
	//
	//   https://www.terraform.io/docs/language/syntax/configuration.html
	//
	// The underlying *Schema is only required to implement Type. ValidateFunc
	// or ValidateDiagFunc can be used to validate each element value.
	//
	// If the Elem is a *Resource, the surrounding Schema represents a
	// configuration block. Blocks can contain underlying attributes or blocks.
	// In practitioner configurations, an equals sign (=) cannot be used to
	// set the value. Blocks are instead repeated as necessary, or require
	// the use of dynamic block expressions. Refer to the following
	// documentation:
	//
	//   https://www.terraform.io/docs/language/syntax/configuration.html
	//   https://www.terraform.io/docs/language/expressions/dynamic-blocks.html
	//
	// The underlying *Resource must only implement the Schema field.
	Elem interface{}

	// MaxItems defines a maximum amount of items that can exist within a
	// TypeSet or TypeList.
	MaxItems int

	// MinItems defines a minimum amount of items that can exist within a
	// TypeSet or TypeList.
	//
	// If the field Optional is set to true then MinItems is ignored and thus
	// effectively zero.
	MinItems int

	// Set defines custom hash algorithm for each TypeSet element. If not
	// defined, the SDK implements a default hash algorithm based on the
	// underlying structure and type information of the Elem field.
	Set SchemaSetFunc

	// ComputedWhen is a set of queries on the configuration. Whenever any
	// of these things is changed, it will require a recompute (this requires
	// that Computed is set to true).
	//
	// Deprecated: This functionality is not implemented and this field
	// declaration should be removed.
	ComputedWhen []string

	// ConflictsWith is a set of attribute paths, including this attribute,
	// whose configurations cannot be set simultaneously. This implements the
	// validation logic declaratively within the schema and can trigger earlier
	// in Terraform operations, rather than using create or update logic which
	// only triggers during apply.
	//
	// Only absolute attribute paths, ones starting with top level attribute
	// names, are supported. Attribute paths cannot be accurately declared
	// for TypeList (if MaxItems is greater than 1), TypeMap, or TypeSet
	// attributes. To reference an attribute under a single configuration block
	// (TypeList with Elem of *Resource and MaxItems of 1), the syntax is
	// "parent_block_name.0.child_attribute_name".
	ConflictsWith []string

	// ExactlyOneOf is a set of attribute paths, including this attribute,
	// where only one attribute out of all specified can be configured. It will
	// return a validation error if none are specified as well. This implements
	// the validation logic declaratively within the schema and can trigger
	// earlier in Terraform operations, rather than using create or update
	// logic which only triggers during apply.
	//
	// Only absolute attribute paths, ones starting with top level attribute
	// names, are supported. Attribute paths cannot be accurately declared
	// for TypeList (if MaxItems is greater than 1), TypeMap, or TypeSet
	// attributes. To reference an attribute under a single configuration block
	// (TypeList with Elem of *Resource and MaxItems of 1), the syntax is
	// "parent_block_name.0.child_attribute_name".
	ExactlyOneOf []string

	// AtLeastOneOf is a set of attribute paths, including this attribute,
	// in which at least one of the attributes must be configured. This
	// implements the validation logic declaratively within the schema and can
	// trigger earlier in Terraform operations, rather than using create or
	// update logic which only triggers during apply.
	//
	// Only absolute attribute paths, ones starting with top level attribute
	// names, are supported. Attribute paths cannot be accurately declared
	// for TypeList (if MaxItems is greater than 1), TypeMap, or TypeSet
	// attributes. To reference an attribute under a single configuration block
	// (TypeList with Elem of *Resource and MaxItems of 1), the syntax is
	// "parent_block_name.0.child_attribute_name".
	AtLeastOneOf []string

	// RequiredWith is a set of attribute paths, including this attribute,
	// that must be set simultaneously. This implements the validation logic
	// declaratively within the schema and can trigger earlier in Terraform
	// operations, rather than using create or update logic which only triggers
	// during apply.
	//
	// Only absolute attribute paths, ones starting with top level attribute
	// names, are supported. Attribute paths cannot be accurately declared
	// for TypeList (if MaxItems is greater than 1), TypeMap, or TypeSet
	// attributes. To reference an attribute under a single configuration block
	// (TypeList with Elem of *Resource and MaxItems of 1), the syntax is
	// "parent_block_name.0.child_attribute_name".
	RequiredWith []string

	// Deprecated defines warning diagnostic details to display when
	// practitioner configurations use this attribute or block. The warning
	// diagnostic summary is automatically set to "Argument is deprecated"
	// along with configuration source file and line information.
	//
	// Set this field to a practitioner actionable message such as:
	//
	//  - "Configure other_attribute instead. This attribute will be removed
	//    in the next major version of the provider."
	//  - "Remove this attribute's configuration as it no longer is used and
	//    the attribute will be removed in the next major version of the
	//    provider."
	//
	// In Terraform 1.2.7 and later, this warning diagnostic is displayed any
	// time a practitioner attempts to configure a known value for this
	// attribute and certain scenarios where this attribute is referenced.
	//
	// In Terraform 1.2.6 and earlier, this warning diagnostic is only
	// displayed when the attribute is Required or Optional, and if the
	// practitioner configuration attempts to set the attribute value to a
	// known value. It cannot detect practitioner configuration values that
	// are unknown ("known after apply").
	//
	// Additional information about deprecation enhancements for read-only
	// attributes can be found in:
	//
	//  - https://github.com/hashicorp/terraform/issues/7569
	Deprecated string

	// ValidateFunc allows individual fields to define arbitrary validation
	// logic. It is yielded the provided config value as an interface{} that is
	// guaranteed to be of the proper Schema type, and it can yield warnings or
	// errors based on inspection of that value.
	//
	// ValidateFunc is honored only when the schema's Type is set to TypeInt,
	// TypeFloat, TypeString, TypeBool, or TypeMap. It is ignored for all other types.
	ValidateFunc SchemaValidateFunc

	// ValidateDiagFunc allows individual fields to define arbitrary validation
	// logic. It is yielded the provided config value as an interface{} that is
	// guaranteed to be of the proper Schema type, and it can yield diagnostics
	// based on inspection of that value.
	//
	// ValidateDiagFunc is honored only when the schema's Type is set to TypeInt,
	// TypeFloat, TypeString, TypeBool, or TypeMap. It is ignored for all other types.
	//
	// ValidateDiagFunc is also yielded the cty.Path the SDK has built up to this
	// attribute. The SDK will automatically set the AttributePath of any returned
	// Diagnostics to this path. Therefore the developer does not need to set
	// the AttributePath for primitive types.
	//
	// In the case of TypeMap to provide the most precise information, please
	// set an AttributePath with the additional cty.IndexStep:
	//
	//  AttributePath: cty.IndexStringPath("key_name")
	//
	// Or alternatively use the passed in path to create the absolute path:
	//
	//  AttributePath: append(path, cty.IndexStep{Key: cty.StringVal("key_name")})
	ValidateDiagFunc SchemaValidateDiagFunc

	// Sensitive ensures that the attribute's value does not get displayed in
	// the Terraform user interface output. It should be used for password or
	// other values which should be hidden.
	//
	// Terraform does not support conditional sensitivity, so if the value may
	// only be sensitive in certain scenarios, a pragmatic choice will be
	// necessary upfront of whether or not to always hide the value. Some
	// providers may opt to split up resources based on sensitivity, to ensure
	// that practitioners without sensitive values do not have values
	// unnecessarily hidden.
	//
	// Terraform does not support passing sensitivity from configurations to
	// providers. For example, if a sensitive value is configured via another
	// attribute, this attribute is not marked Sensitive, and the value is used
	// in this attribute value, the sensitivity is not transitive. The value
	// will be displayed as normal.
	//
	// Sensitive values propagate when referenced in other parts of a
	// configuration unless the nonsensitive() configuration function is used.
	// Certain configuration usage may also expand the sensitivity. For
	// example, including the sensitive value in a set may mark the whole set
	// as sensitive. Any outputs containing a sensitive value must enable the
	// output sensitive argument.
	Sensitive bool
}

Schema describes the structure and type information of a value, whether sourced from configuration, plan, or state data. Schema is used in Provider and Resource types (for managed resources and data resources) and is fundamental to the implementations of ResourceData and ResourceDiff.

The Type field must always be set. At least one of Required, Optional, Optional and Computed, or Computed must be enabled unless the Schema is directly an implementation of an Elem field of another Schema.

func (*Schema) DefaultValue

func (s *Schema) DefaultValue() (interface{}, error)

Returns a default value for this schema by either reading Default or evaluating DefaultFunc. If neither of these are defined, returns nil.

func (*Schema) GoString

func (s *Schema) GoString() string

func (*Schema) ZeroValue

func (s *Schema) ZeroValue() interface{}

Returns a zero value for the schema.

type SchemaConfigMode

type SchemaConfigMode int

SchemaConfigMode is used to influence how a schema item is mapped into a corresponding configuration construct, using the ConfigMode field of Schema.

const (
	SchemaConfigModeAuto SchemaConfigMode = iota
	SchemaConfigModeAttr
	SchemaConfigModeBlock
)

type SchemaDefaultFunc

type SchemaDefaultFunc func() (interface{}, error)

SchemaDefaultFunc is a function called to return a default value for a field.

func EnvDefaultFunc

func EnvDefaultFunc(k string, dv interface{}) SchemaDefaultFunc

EnvDefaultFunc is a helper function that returns the value of the given environment variable, if one exists, or the default value otherwise.

func MultiEnvDefaultFunc

func MultiEnvDefaultFunc(ks []string, dv interface{}) SchemaDefaultFunc

MultiEnvDefaultFunc is a helper function that returns the value of the first environment variable in the given list that returns a non-empty value. If none of the environment variables return a value, the default value is returned.

type SchemaDiffSuppressFunc

type SchemaDiffSuppressFunc func(k, oldValue, newValue string, d *ResourceData) bool

SchemaDiffSuppressFunc is a function which can be used to determine whether a detected diff on a schema element is "valid" or not, and suppress it from the plan if necessary.

Return true if the diff should be suppressed, false to retain it.

type SchemaSetFunc

type SchemaSetFunc func(interface{}) int

SchemaSetFunc is a function that must return a unique ID for the given element. This unique ID is used to store the element in a hash.

func HashResource

func HashResource(resource *Resource) SchemaSetFunc

HashResource hashes complex structures that are described using a *Resource. This is the default set implementation used when a set's element type is a full resource.

func HashSchema

func HashSchema(schema *Schema) SchemaSetFunc

HashSchema hashes values that are described using a *Schema. This is the default set implementation used when a set's element type is a single schema.

type SchemaStateFunc

type SchemaStateFunc func(interface{}) string

SchemaStateFunc is a function used to convert some type to a string to be stored in the state.

type SchemaValidateDiagFunc

type SchemaValidateDiagFunc func(interface{}, cty.Path) diag.Diagnostics

SchemaValidateDiagFunc is a function used to validate a single field in the schema and has Diagnostic support.

type SchemaValidateFunc deprecated

type SchemaValidateFunc func(interface{}, string) ([]string, []error)

SchemaValidateFunc is a function used to validate a single field in the schema.

Deprecated: please use SchemaValidateDiagFunc

type Set

type Set struct {
	F SchemaSetFunc
	// contains filtered or unexported fields
}

Set is a set data structure that is returned for elements of type TypeSet.

func CopySet

func CopySet(otherSet *Set) *Set

CopySet returns a copy of another set.

func NewSet

func NewSet(f SchemaSetFunc, items []interface{}) *Set

NewSet is a convenience method for creating a new set with the given items.

func (*Set) Add

func (s *Set) Add(item interface{})

Add adds an item to the set if it isn't already in the set.

func (*Set) Contains

func (s *Set) Contains(item interface{}) bool

Contains checks if the set has the given item.

func (*Set) Difference

func (s *Set) Difference(other *Set) *Set

Difference performs a set difference of the two sets, returning a new third set that has only the elements unique to this set.

func (*Set) Equal

func (s *Set) Equal(raw interface{}) bool

func (*Set) GoString

func (s *Set) GoString() string

func (*Set) HashEqual

func (s *Set) HashEqual(raw interface{}) bool

HashEqual simply checks to the keys the top-level map to the keys in the other set's top-level map to see if they are equal. This obviously assumes you have a properly working hash function - use HashResource if in doubt.

func (*Set) Intersection

func (s *Set) Intersection(other *Set) *Set

Intersection performs the set intersection of the two sets and returns a new third set.

func (*Set) Len

func (s *Set) Len() int

Len returns the amount of items in the set.

func (*Set) List

func (s *Set) List() []interface{}

List returns the elements of this set in slice format.

The order of the returned elements is deterministic. Given the same set, the order of this will always be the same.

func (*Set) Remove

func (s *Set) Remove(item interface{})

Remove removes an item if it's already in the set. Idempotent.

func (*Set) Union

func (s *Set) Union(other *Set) *Set

Union performs the set union of the two sets and returns a new third set.

type StateContextFunc

type StateContextFunc func(context.Context, *ResourceData, interface{}) ([]*ResourceData, error)

StateContextFunc is the function called to import a resource into the Terraform state. It is given a ResourceData with only ID set. This ID is going to be an arbitrary value given by the user and may not map directly to the ID format that the resource expects, so that should be validated.

This should return a slice of ResourceData that turn into the state that was imported. This might be as simple as returning only the argument that was given to the function. In other cases (such as AWS security groups), an import may fan out to multiple resources and this will have to return multiple.

To create the ResourceData structures for other resource types (if you have to), instantiate your resource and call the Data function.

type StateFunc deprecated

type StateFunc func(*ResourceData, interface{}) ([]*ResourceData, error)

StateFunc is the function called to import a resource into the Terraform state.

Deprecated: Please use the context aware equivalent StateContextFunc.

type StateMigrateFunc

type StateMigrateFunc func(
	int, *terraform.InstanceState, interface{}) (*terraform.InstanceState, error)

See Resource documentation.

type StateUpgradeFunc

type StateUpgradeFunc func(ctx context.Context, rawState map[string]interface{}, meta interface{}) (map[string]interface{}, error)

Function signature for a schema version state upgrade handler.

The Context parameter stores SDK information, such as loggers. It also is wired to receive any cancellation from Terraform such as a system or practitioner sending SIGINT (Ctrl-c).

The map[string]interface{} parameter contains the previous schema version state data for a managed resource instance. The keys are top level attribute or block names mapped to values that can be type asserted similar to fetching values using the ResourceData Get* methods:

  • TypeBool: bool
  • TypeFloat: float
  • TypeInt: int
  • TypeList: []interface{}
  • TypeMap: map[string]interface{}
  • TypeSet: *Set
  • TypeString: string

In certain scenarios, the map may be nil, so checking for that condition upfront is recommended to prevent potential panics.

The interface{} parameter is the result of the Provider type ConfigureFunc field execution. If the Provider does not define a ConfigureFunc, this will be nil. This parameter is conventionally used to store API clients and other provider instance specific data.

The map[string]interface{} return parameter should contain the upgraded schema version state data for a managed resource instance. Values must align to the typing mentioned above.

type StateUpgrader

type StateUpgrader struct {
	// Version is the version schema that this Upgrader will handle, converting
	// it to Version+1.
	Version int

	// Type describes the schema that this function can upgrade. Type is
	// required to decode the schema if the state was stored in a legacy
	// flatmap format.
	Type cty.Type

	// Upgrade takes the JSON encoded state and the provider meta value, and
	// upgrades the state one single schema version. The provided state is
	// deocded into the default json types using a map[string]interface{}. It
	// is up to the StateUpgradeFunc to ensure that the returned value can be
	// encoded using the new schema.
	Upgrade StateUpgradeFunc
}

Implementation of a single schema version state upgrade.

type StringKind

type StringKind configschema.StringKind

StringKind represents the format a string is in.

type UpdateContextFunc

type UpdateContextFunc func(context.Context, *ResourceData, interface{}) diag.Diagnostics

See Resource documentation.

type UpdateFunc deprecated

type UpdateFunc func(*ResourceData, interface{}) error

Deprecated: Please use the context aware equivalents instead.

type ValueType

type ValueType int

ValueType is an enum of the type that can be represented by a schema.

const (
	TypeInvalid ValueType = iota
	TypeBool
	TypeInt
	TypeFloat
	TypeString
	TypeList
	TypeMap
	TypeSet
)

func (ValueType) String

func (i ValueType) String() string

func (ValueType) Zero

func (t ValueType) Zero() interface{}

Zero returns the zero value for a type.

Jump to

Keyboard shortcuts

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