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
- Variables
- func DefaultTimeout(tx interface{}) *time.Duration
- func HashString(v interface{}) int
- func Noop(*ResourceData, interface{}) error
- func RemoveFromState(d *ResourceData, _ interface{}) error
- func SerializeResourceForHash(buf *bytes.Buffer, val interface{}, resource *Resource)
- func SerializeValueForHash(buf *bytes.Buffer, val interface{}, schema *Schema)
- type Backend
- type BasicMapReader
- type ConfigFieldReader
- type ConfigureFunc
- type CreateFunc
- type DeleteFunc
- type DiffFieldReader
- type Equal
- type ExistsFunc
- type FieldReadResult
- type FieldReader
- type FieldWriter
- type MapFieldReader
- type MapFieldWriter
- type MapReader
- type MultiLevelFieldReader
- type MultiMapReader
- type Provider
- func (p *Provider) Apply(info *terraform.InstanceInfo, s *terraform.InstanceState, ...) (*terraform.InstanceState, error)
- func (p *Provider) Configure(c *terraform.ResourceConfig) error
- func (p *Provider) DataSources() []terraform.DataSource
- func (p *Provider) Diff(info *terraform.InstanceInfo, s *terraform.InstanceState, ...) (*terraform.InstanceDiff, error)
- func (p *Provider) ImportState(info *terraform.InstanceInfo, id string) ([]*terraform.InstanceState, error)
- func (p *Provider) Input(input terraform.UIInput, c *terraform.ResourceConfig) (*terraform.ResourceConfig, error)
- func (p *Provider) InternalValidate() error
- func (p *Provider) Meta() interface{}
- func (p *Provider) ReadDataApply(info *terraform.InstanceInfo, d *terraform.InstanceDiff) (*terraform.InstanceState, error)
- func (p *Provider) ReadDataDiff(info *terraform.InstanceInfo, c *terraform.ResourceConfig) (*terraform.InstanceDiff, error)
- func (p *Provider) Refresh(info *terraform.InstanceInfo, s *terraform.InstanceState) (*terraform.InstanceState, error)
- func (p *Provider) Resources() []terraform.ResourceType
- func (p *Provider) SetMeta(v interface{})
- func (p *Provider) Stop() error
- func (p *Provider) StopContext() context.Context
- func (p *Provider) Stopped() bool
- func (p *Provider) TestReset() error
- func (p *Provider) Validate(c *terraform.ResourceConfig) ([]string, []error)
- func (p *Provider) ValidateDataSource(t string, c *terraform.ResourceConfig) ([]string, []error)
- func (p *Provider) ValidateResource(t string, c *terraform.ResourceConfig) ([]string, []error)
- type Provisioner
- func (p *Provisioner) Apply(o terraform.UIOutput, s *terraform.InstanceState, c *terraform.ResourceConfig) error
- func (p *Provisioner) InternalValidate() error
- func (p *Provisioner) Stop() error
- func (p *Provisioner) StopContext() context.Context
- func (p *Provisioner) Validate(c *terraform.ResourceConfig) (ws []string, es []error)
- type ReadFunc
- type Resource
- func (r *Resource) Apply(s *terraform.InstanceState, d *terraform.InstanceDiff, meta interface{}) (*terraform.InstanceState, error)
- func (r *Resource) Data(s *terraform.InstanceState) *ResourceData
- func (r *Resource) Diff(s *terraform.InstanceState, c *terraform.ResourceConfig) (*terraform.InstanceDiff, error)
- func (r *Resource) InternalValidate(topSchemaMap schemaMap, writable bool) error
- func (r *Resource) ReadDataApply(d *terraform.InstanceDiff, meta interface{}) (*terraform.InstanceState, error)
- func (r *Resource) Refresh(s *terraform.InstanceState, meta interface{}) (*terraform.InstanceState, error)
- func (r *Resource) TestResourceData() *ResourceData
- func (r *Resource) Validate(c *terraform.ResourceConfig) ([]string, []error)
- type ResourceData
- func (d *ResourceData) ConnInfo() map[string]string
- func (d *ResourceData) Get(key string) interface{}
- func (d *ResourceData) GetChange(key string) (interface{}, interface{})
- func (d *ResourceData) GetOk(key string) (interface{}, bool)
- func (d *ResourceData) GetOkExists(key string) (interface{}, bool)
- func (d *ResourceData) HasChange(key string) bool
- func (d *ResourceData) Id() string
- func (d *ResourceData) IsNewResource() bool
- func (d *ResourceData) MarkNewResource()
- func (d *ResourceData) Partial(on bool)
- func (d *ResourceData) Set(key string, value interface{}) error
- func (d *ResourceData) SetConnInfo(v map[string]string)
- func (d *ResourceData) SetId(v string)
- func (d *ResourceData) SetPartial(k string)
- func (d *ResourceData) SetType(t string)
- func (d *ResourceData) State() *terraform.InstanceState
- func (d *ResourceData) Timeout(key string) time.Duration
- func (d *ResourceData) UnsafeSetFieldRaw(key string, value string)
- type ResourceImporter
- type ResourceTimeout
- func (t *ResourceTimeout) ConfigDecode(s *Resource, c *terraform.ResourceConfig) error
- func (t *ResourceTimeout) DiffDecode(is *terraform.InstanceDiff) error
- func (t *ResourceTimeout) DiffEncode(id *terraform.InstanceDiff) error
- func (t *ResourceTimeout) StateDecode(id *terraform.InstanceState) error
- func (t *ResourceTimeout) StateEncode(is *terraform.InstanceState) error
- type Schema
- type SchemaDefaultFunc
- type SchemaDiffSuppressFunc
- type SchemaSetFunc
- type SchemaStateFunc
- type SchemaValidateFunc
- type Set
- func (s *Set) Add(item interface{})
- func (s *Set) Contains(item interface{}) bool
- func (s *Set) Difference(other *Set) *Set
- func (s *Set) Equal(raw interface{}) bool
- func (s *Set) GoString() string
- func (s *Set) HashEqual(raw interface{}) bool
- func (s *Set) Intersection(other *Set) *Set
- func (s *Set) Len() int
- func (s *Set) List() []interface{}
- func (s *Set) Remove(item interface{})
- func (s *Set) Union(other *Set) *Set
- type StateFunc
- type StateMigrateFunc
- type UpdateFunc
- type ValueType
Constants ¶
const ( TimeoutCreate = "create" TimeoutRead = "read" TimeoutUpdate = "update" TimeoutDelete = "delete" TimeoutDefault = "default" )
const TimeoutKey = "e2bfb730-ecaa-11e6-8f88-34363bc7c4c0"
const TimeoutsConfigKey = "timeouts"
Variables ¶
var ( // This returns a *ResourceData for the connection information. // Guaranteed to never be nil. ProvConnDataKey = contextKey("provider conn data") // This returns a *ResourceData for the config information. // Guaranteed to never be nil. ProvConfigDataKey = contextKey("provider config data") // This returns a terraform.UIOutput. Guaranteed to never be nil. ProvOutputKey = contextKey("provider output") // This returns the raw InstanceState passed to Apply. Guaranteed to // be set, but may be nil. ProvRawStateKey = contextKey("provider raw state") )
Keys that can be used to access data in the context parameters for Provisioners.
Functions ¶
func DefaultTimeout ¶ added in v0.9.0
could be time.Duration, int64 or float64
func HashString ¶ added in v0.5.0
func HashString(v interface{}) int
HashString hashes strings. If you want a Set of strings, this is the SchemaSetFunc you want.
func Noop ¶ added in v0.7.8
func Noop(*ResourceData, interface{}) error
Noop is a convenience implementation of resource function which takes no action and returns no error.
func RemoveFromState ¶ added in v0.7.8
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 ¶ added in v0.6.4
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 ¶ added in v0.6.4
Types ¶
type Backend ¶ added in v0.9.0
type Backend struct { // Schema is the schema for the configuration of this backend. If this // Backend has no configuration this can be omitted. Schema map[string]*Schema // ConfigureFunc is called to configure the backend. Use the // FromContext* methods to extract information from the context. // This can be nil, in which case nothing will be called but the // config will still be stored. ConfigureFunc func(context.Context) error // contains filtered or unexported fields }
Backend represents a partial backend.Backend implementation and simplifies the creation of configuration loading and validation.
Unlike other schema structs such as Provider, this struct is meant to be embedded within your actual implementation. It provides implementations only for Input and Configure and gives you a method for accessing the configuration in the form of a ResourceData that you're expected to call from the other implementation funcs.
func (*Backend) Config ¶ added in v0.9.0
func (b *Backend) Config() *ResourceData
Config returns the configuration. This is available after Configure is called.
func (*Backend) Configure ¶ added in v0.9.0
func (b *Backend) Configure(c *terraform.ResourceConfig) error
func (*Backend) Input ¶ added in v0.9.0
func (b *Backend) Input( input terraform.UIInput, c *terraform.ResourceConfig) (*terraform.ResourceConfig, error)
type BasicMapReader ¶ added in v0.3.7
BasicMapReader implements MapReader for a single map.
type ConfigFieldReader ¶ added in v0.3.7
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 ¶ added in v0.3.7
func (r *ConfigFieldReader) ReadField(address []string) (FieldReadResult, error)
type ConfigureFunc ¶
type ConfigureFunc func(*ResourceData) (interface{}, error)
ConfigureFunc 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 CreateFunc ¶
type CreateFunc func(*ResourceData, interface{}) error
See Resource documentation.
type DeleteFunc ¶
type DeleteFunc func(*ResourceData, interface{}) error
See Resource documentation.
type DiffFieldReader ¶ added in v0.3.7
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 ¶ added in v0.3.7
func (r *DiffFieldReader) ReadField(address []string) (FieldReadResult, error)
type Equal ¶ added in v0.3.7
type Equal interface {
Equal(interface{}) bool
}
Equal is an interface that checks for deep equality between two objects.
type ExistsFunc ¶ added in v0.3.7
type ExistsFunc func(*ResourceData, interface{}) (bool, error)
See Resource documentation.
type FieldReadResult ¶ added in v0.3.7
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 ¶ added in v0.3.7
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 ¶ added in v0.3.7
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 ¶ added in v0.3.7
FieldWriters are responsible for writing fields by address into a proper typed representation. ResourceData uses this to write new data into existing sources.
type MapFieldReader ¶ added in v0.3.7
MapFieldReader reads fields out of an untyped map[string]string to the best of its ability.
func (*MapFieldReader) ReadField ¶ added in v0.3.7
func (r *MapFieldReader) ReadField(address []string) (FieldReadResult, error)
type MapFieldWriter ¶ added in v0.3.7
MapFieldWriter writes data into a single map[string]string structure.
func (*MapFieldWriter) Map ¶ added in v0.3.7
func (w *MapFieldWriter) Map() map[string]string
Map returns the underlying map that is being written to.
func (*MapFieldWriter) WriteField ¶ added in v0.3.7
func (w *MapFieldWriter) WriteField(addr []string, value interface{}) error
type MapReader ¶ added in v0.3.7
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 ¶ added in v0.3.7
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 ¶ added in v0.3.7
func (r *MultiLevelFieldReader) ReadField(address []string) (FieldReadResult, error)
func (*MultiLevelFieldReader) ReadFieldExact ¶ added in v0.3.7
func (r *MultiLevelFieldReader) ReadFieldExact( address []string, level string) (FieldReadResult, error)
func (*MultiLevelFieldReader) ReadFieldMerge ¶ added in v0.3.7
func (r *MultiLevelFieldReader) ReadFieldMerge( address []string, level string) (FieldReadResult, error)
type MultiMapReader ¶ added in v0.3.7
MultiMapReader reads over multiple maps, preferring keys that are founder earlier (lower number index) vs. later (higher number index)
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 // ConfigureFunc is a function for configuring the provider. If the // provider doesn't need to be configured, this can be omitted. // // See the ConfigureFunc documentation for more information. ConfigureFunc ConfigureFunc // MetaReset is called by TestReset to reset any state stored in the meta // interface. This is especially important if the StopContext is stored by // the provider. MetaReset func() error // 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) Apply ¶
func (p *Provider) Apply( info *terraform.InstanceInfo, s *terraform.InstanceState, d *terraform.InstanceDiff) (*terraform.InstanceState, error)
Apply implementation of terraform.ResourceProvider interface.
func (*Provider) Configure ¶
func (p *Provider) Configure(c *terraform.ResourceConfig) error
Configure implementation of terraform.ResourceProvider interface.
func (*Provider) DataSources ¶ added in v0.7.1
func (p *Provider) DataSources() []terraform.DataSource
DataSources implementation of terraform.ResourceProvider interface.
func (*Provider) Diff ¶
func (p *Provider) Diff( info *terraform.InstanceInfo, s *terraform.InstanceState, c *terraform.ResourceConfig) (*terraform.InstanceDiff, error)
Diff implementation of terraform.ResourceProvider interface.
func (*Provider) ImportState ¶ added in v0.7.1
func (p *Provider) ImportState( info *terraform.InstanceInfo, id string) ([]*terraform.InstanceState, error)
func (*Provider) Input ¶ added in v0.3.0
func (p *Provider) Input( input terraform.UIInput, c *terraform.ResourceConfig) (*terraform.ResourceConfig, error)
Input implementation of terraform.ResourceProvider interface.
func (*Provider) InternalValidate ¶
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) ReadDataApply ¶ added in v0.7.1
func (p *Provider) ReadDataApply( info *terraform.InstanceInfo, d *terraform.InstanceDiff) (*terraform.InstanceState, error)
RefreshData implementation of terraform.ResourceProvider interface.
func (*Provider) ReadDataDiff ¶ added in v0.7.1
func (p *Provider) ReadDataDiff( info *terraform.InstanceInfo, c *terraform.ResourceConfig) (*terraform.InstanceDiff, error)
ReadDataDiff implementation of terraform.ResourceProvider interface.
func (*Provider) Refresh ¶
func (p *Provider) Refresh( info *terraform.InstanceInfo, s *terraform.InstanceState) (*terraform.InstanceState, error)
Refresh implementation of terraform.ResourceProvider interface.
func (*Provider) Resources ¶
func (p *Provider) Resources() []terraform.ResourceType
Resources implementation of terraform.ResourceProvider interface.
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) Stop ¶ added in v0.8.2
Stop implementation of terraform.ResourceProvider interface.
func (*Provider) StopContext ¶ added in v0.8.2
StopCh returns a channel that is closed once the provider is stopped.
func (*Provider) Stopped ¶ added in v0.8.2
Stopped reports whether the provider has been stopped or not.
func (*Provider) TestReset ¶ added in v0.9.0
TestReset resets any state stored in the Provider, and will call TestReset on Meta if it implements the TestProvider interface. This may be used to reset the schema.Provider at the start of a test, and is automatically called by resource.Test.
func (*Provider) Validate ¶
func (p *Provider) Validate(c *terraform.ResourceConfig) ([]string, []error)
Validate implementation of terraform.ResourceProvider interface.
func (*Provider) ValidateDataSource ¶ added in v0.7.1
ValidateDataSource implementation of terraform.ResourceProvider interface.
func (*Provider) ValidateResource ¶
ValidateResource implementation of terraform.ResourceProvider interface.
type Provisioner ¶ added in v0.9.0
type Provisioner struct { // ConnSchema is the schema for the connection settings for this // provisioner. // // The keys of this map are the configuration keys, and the value is // the schema describing the value of the configuration. // // NOTE: The value of connection keys can only be strings for now. ConnSchema map[string]*Schema // Schema is the schema for the usage of this provisioner. // // 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 // ApplyFunc is the function for executing the provisioner. This is required. // It is given a context. See the Provisioner struct docs for more // information. ApplyFunc func(ctx context.Context) error // ValidateFunc is a function for extended validation. This is optional // and should be used when individual field validation is not enough. ValidateFunc func(*terraform.ResourceConfig) ([]string, []error) // contains filtered or unexported fields }
Provisioner represents a resource provisioner in Terraform and properly implements all of the ResourceProvisioner API.
This higher level structure makes it much easier to implement a new or custom provisioner for Terraform.
The function callbacks for this structure are all passed a context object. This context object has a number of pre-defined values that can be accessed via the global functions defined in context.go.
func (*Provisioner) Apply ¶ added in v0.9.0
func (p *Provisioner) Apply( o terraform.UIOutput, s *terraform.InstanceState, c *terraform.ResourceConfig) error
Apply implementation of terraform.ResourceProvisioner interface.
func (*Provisioner) InternalValidate ¶ added in v0.9.0
func (p *Provisioner) InternalValidate() error
InternalValidate should be called to validate the structure of the provisioner.
This should be called in a unit test to verify before release that this structure is properly configured for use.
func (*Provisioner) Stop ¶ added in v0.9.0
func (p *Provisioner) Stop() error
Stop implementation of terraform.ResourceProvisioner interface.
func (*Provisioner) StopContext ¶ added in v0.9.0
func (p *Provisioner) StopContext() context.Context
StopContext returns a context that checks whether a provisioner is stopped.
func (*Provisioner) Validate ¶ added in v0.9.0
func (p *Provisioner) Validate(c *terraform.ResourceConfig) (ws []string, es []error)
Validate implements the terraform.ResourceProvisioner interface.
type Resource ¶
type Resource struct { // Schema is the schema for the configuration of this resource. // // The keys of this map are the configuration keys, and the values // describe the schema of the configuration value. // // The schema is used to represent both configurable data as well // as data that might be computed in the process of creating this // resource. Schema map[string]*Schema // SchemaVersion is the version number for this resource's Schema // definition. The current SchemaVersion stored in the state for each // resource. Provider authors can increment this version number // when Schema semantics change. If the State's SchemaVersion is less than // the current SchemaVersion, the InstanceState is yielded to the // MigrateState callback, where the provider can make whatever changes it // needs to update the state to be compatible to the latest version of the // Schema. // // 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. // // 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. MigrateState StateMigrateFunc // The functions below are the CRUD operations for this resource. // // The only optional operation is Update. If Update is not implemented, // then updates will not be supported for this resource. // // The ResourceData parameter in the functions below are used to // query configuration and changes for the resource as well as to set // the ID, computed data, etc. // // The interface{} parameter is the result of the ConfigureFunc in // the provider for this resource. If the provider does not define // a ConfigureFunc, this will be nil. This parameter should be used // to store API clients, configuration structures, etc. // // If any errors occur during each of the operation, an error should be // returned. If a resource was partially updated, be careful to enable // partial state mode for ResourceData and use it accordingly. // // Exists is a function that is called to check if a resource still // exists. If this returns false, then this will affect the diff // accordingly. If this function isn't set, it will not be called. It // is highly recommended to set it. The *ResourceData passed to Exists // should _not_ be modified. Create CreateFunc Read ReadFunc Update UpdateFunc Delete DeleteFunc Exists ExistsFunc // Importer is the ResourceImporter implementation for this 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 // Timeouts allow users to specify specific time durations in which an // operation should time out, to allow them to extend an action to suit their // usage. For example, a user may specify a large Creation timeout for their // AWS RDS Instance due to it's size, or restoring from a snapshot. // Resource implementors must enable Timeout support by adding the allowed // actions (Create, Read, Update, Delete, Default) to the Resource struct, and // accessing them in the matching methods. Timeouts *ResourceTimeout // contains filtered or unexported fields }
Resource represents a thing in Terraform that has a set of configurable attributes and a lifecycle (create, read, update, delete).
The Resource schema is an abstraction that allows provider writers to worry only about CRUD operations while off-loading validation, diff generation, etc. to this higher level library.
In spite of the name, this struct is not used only for terraform resources, but also for data sources. In the case of data sources, the Create, Update and Delete functions must not be provided.
func DataSourceResourceShim ¶ added in v0.7.1
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 ¶
func (r *Resource) Apply( s *terraform.InstanceState, d *terraform.InstanceDiff, meta interface{}) (*terraform.InstanceState, error)
Apply creates, updates, and/or deletes a resource.
func (*Resource) Data ¶ added in v0.7.1
func (r *Resource) Data(s *terraform.InstanceState) *ResourceData
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( s *terraform.InstanceState, c *terraform.ResourceConfig) (*terraform.InstanceDiff, error)
Diff returns a diff of this resource and is API compatible with the ResourceProvider interface.
func (*Resource) InternalValidate ¶
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 ¶ added in v0.7.1
func (r *Resource) ReadDataApply( d *terraform.InstanceDiff, meta interface{}, ) (*terraform.InstanceState, error)
ReadDataApply loads the data for a data source, given a diff that describes the configuration arguments and desired computed attributes.
func (*Resource) Refresh ¶
func (r *Resource) Refresh( s *terraform.InstanceState, meta interface{}) (*terraform.InstanceState, error)
Refresh refreshes the state of the resource.
func (*Resource) TestResourceData ¶ added in v0.6.11
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.
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 check for changes, define partial state updates, etc.
The most relevant methods to take a look at are Get, Set, and Partial.
func FromContextBackendConfig ¶ added in v0.9.0
func FromContextBackendConfig(ctx context.Context) *ResourceData
FromContextBackendConfig extracts a ResourceData with the configuration from the context. This should only be called by Backend functions.
func ImportStatePassthrough ¶ added in v0.7.1
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. This should be used only in the case that an ID-only refresh is possible.
func TestResourceDataRaw ¶ added in v0.9.0
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 ¶ added in v0.10.1
func (d *ResourceData) GetOkExists(key string) (interface{}, bool)
GetOkExists returns the data for a given key and whether or not the key has been set to a non-zero value. This is only useful for determining if boolean attributes have been set, if they are Optional but do not have a Default value.
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. This should only be used if absolutely required/needed.
func (*ResourceData) HasChange ¶
func (d *ResourceData) HasChange(key string) bool
HasChange returns whether or not the given key has been changed.
func (*ResourceData) IsNewResource ¶ added in v0.6.14
func (d *ResourceData) IsNewResource() bool
func (*ResourceData) MarkNewResource ¶ added in v0.6.14
func (d *ResourceData) MarkNewResource()
func (*ResourceData) Partial ¶
func (d *ResourceData) Partial(on bool)
Partial turns partial state mode on/off.
When partial state mode is enabled, then only key prefixes specified by SetPartial will be in the final state. This allows providers to return partial states for partially applied resources (when errors occur).
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) SetPartial ¶
func (d *ResourceData) SetPartial(k string)
SetPartial adds the key to the final state output while in partial state mode. The key must be a root key in the schema (i.e. it cannot be "list.0").
If partial state mode is disabled, then this has no effect. Additionally, whenever partial state mode is toggled, the partial data is cleared.
func (*ResourceData) SetType ¶ added in v0.7.1
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 ¶ added in v0.9.0
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.
func (*ResourceData) UnsafeSetFieldRaw ¶ added in v0.7.1
func (d *ResourceData) UnsafeSetFieldRaw(key string, value string)
UnsafeSetFieldRaw allows setting arbitrary values in state to arbitrary values, bypassing schema. This MUST NOT be used in normal circumstances - it exists only to support the remote_state data source.
type ResourceImporter ¶ added in v0.7.1
type ResourceImporter struct { // State 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. State StateFunc }
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 ¶ added in v0.7.1
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 ¶ added in v0.9.0
func (*ResourceTimeout) ConfigDecode ¶ added in v0.9.0
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 ¶ added in v0.9.0
func (t *ResourceTimeout) DiffDecode(is *terraform.InstanceDiff) error
func (*ResourceTimeout) DiffEncode ¶ added in v0.9.0
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 ¶ added in v0.9.0
func (t *ResourceTimeout) StateDecode(id *terraform.InstanceState) error
func (*ResourceTimeout) StateEncode ¶ added in v0.9.0
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 // If one of these is set, then this item can come from the configuration. // Both cannot be set. If Optional is set, the value is optional. If // Required is set, the value is required. // // One of these must be set if the value is not computed. That is: // value either comes from the config, is computed, or is both. Optional bool Required 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. DiffSuppressFunc SchemaDiffSuppressFunc // If this is non-nil, then this will be a default value that is used // when this item is not set in the configuration. // // DefaultFunc can be specified to compute a dynamic default. // Only one of Default or DefaultFunc can be set. If DefaultFunc is // used then its return value should be stable to avoid generating // confusing/perpetual diffs. // // Changing either Default or the return value of DefaultFunc can be // a breaking change, especially if the attribute in question has // ForceNew set. If a default needs to change to align with changing // assumptions in an upstream API then it may be necessary to also use // the MigrateState function on the resource to change the state to match, // or have the Read function adjust the state value to align with the // new default. // // If Required is true above, then Default cannot be set. DefaultFunc // can be set with Required. If the DefaultFunc returns nil, then there // will be no default and the user will be asked to fill it in. // // If either of these is set, then the user won't be asked for input // for this key if the default is not nil. Default interface{} DefaultFunc SchemaDefaultFunc // Description is used as the description for docs or asking for user // input. It should be relatively short (a few sentences max) and should // be formatted to fit a CLI. 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 // The fields below relate to diffs. // // If Computed is true, then the result of this value is computed // (unless specified by config) on creation. // // If ForceNew is true, then a change in this resource necessitates // the creation of a new resource. // // 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. Computed bool ForceNew bool StateFunc SchemaStateFunc // The following fields are only set for a TypeList or TypeSet Type. // // Elem must be either a *Schema or a *Resource only if the Type is // TypeList, and represents what the element type is. If it is *Schema, // the element type is just a simple value. If it is *Resource, the // element type is a complex structure, potentially with its own lifecycle. // // MaxItems defines a maximum amount of items that can exist within a // TypeSet or TypeList. Specific use cases would be if a TypeSet is being // used to wrap a complex structure, however more than one instance would // cause instability. // // MinItems defines a minimum amount of items that can exist within a // TypeSet or TypeList. Specific use cases would be if a TypeSet is being // used to wrap a complex structure, however less than one instance would // cause instability. // // PromoteSingle, if true, will allow single elements to be standalone // and promote them to a list. For example "foo" would be promoted to // ["foo"] automatically. This is primarily for legacy reasons and the // ambiguity is not recommended for new usage. Promotion is only allowed // for primitive element types. Elem interface{} MaxItems int MinItems int PromoteSingle bool // The following fields are only valid for a TypeSet type. // // Set defines a function to determine the unique ID of an item so that // a proper set can be built. 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). // // NOTE: This currently does not work. ComputedWhen []string // ConflictsWith is a set of schema keys that conflict with this schema. // This will only check that they're set in the _config_. This will not // raise an error for a malfunctioning resource that sets a conflicting // key. ConflictsWith []string // When Deprecated is set, this attribute is deprecated. // // A deprecated field still works, but will probably stop working in near // future. This string is the message shown to the user with instructions on // how to address the deprecation. Deprecated string // When Removed is set, this attribute has been removed from the schema // // Removed attributes can be left in the Schema to generate informative error // messages for the user when they show up in resource configurations. // This string is the message shown to the user with instructions on // what do to about the removed attribute. Removed 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 currently only works for primitive types. ValidateFunc SchemaValidateFunc // Sensitive ensures that the attribute's value does not get displayed in // logs or regular output. It should be used for passwords or other // secret fields. Future versions of Terraform may encrypt these // values. Sensitive bool }
Schema is used to describe the structure of a value.
Read the documentation of the struct elements for important details.
func (*Schema) DefaultValue ¶ added in v0.3.7
Returns a default value for this schema by either reading Default or evaluating DefaultFunc. If neither of these are defined, returns nil.
type SchemaDefaultFunc ¶ added in v0.3.0
type SchemaDefaultFunc func() (interface{}, error)
SchemaDefaultFunc is a function called to return a default value for a field.
func EnvDefaultFunc ¶ added in v0.3.7
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 ¶ added in v0.3.7
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 ¶ added in v0.7.3
type SchemaDiffSuppressFunc func(k, old, new string, d *ResourceData) bool
SchemaDiffSuppresFunc 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 ¶ added in v0.6.4
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 ¶ added in v0.6.4
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 SchemaValidateFunc ¶ added in v0.6.0
SchemaValidateFunc is a function used to validate a single field in the schema.
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 NewSet ¶ added in v0.3.1
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) Difference ¶
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) HashEqual ¶ added in v0.10.3
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 ¶
Intersection performs the set intersection of the two sets and returns a new third 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.
type StateFunc ¶ added in v0.7.1
type StateFunc func(*ResourceData, interface{}) ([]*ResourceData, error)
StateFunc 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 StateMigrateFunc ¶ added in v0.4.0
type StateMigrateFunc func( int, *terraform.InstanceState, interface{}) (*terraform.InstanceState, error)
See Resource documentation.
type UpdateFunc ¶
type UpdateFunc func(*ResourceData, interface{}) error
See Resource documentation.
Source Files ¶
- backend.go
- data_source_resource_shim.go
- equal.go
- field_reader.go
- field_reader_config.go
- field_reader_diff.go
- field_reader_map.go
- field_reader_multi.go
- field_writer.go
- field_writer_map.go
- getsource_string.go
- provider.go
- provisioner.go
- resource.go
- resource_data.go
- resource_data_get_source.go
- resource_importer.go
- resource_timeout.go
- schema.go
- serialize.go
- set.go
- testing.go
- valuetype.go
- valuetype_string.go