resource

package
v0.11.0 Latest Latest
Warning

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

Go to latest
Published: Aug 11, 2022 License: MPL-2.0 Imports: 11 Imported by: 364

Documentation

Overview

Package resource contains all interfaces, request types, and response types for a managed resource implementation.

In Terraform, a managed resource is a concept which enables provider developers to offer practitioners full lifecycle management (create, read, update, and delete) of a infrastructure component. Managed resources can also stand in for one-time infrastructure operations that require tracking, by implementing create logic, while omitting update and delete logic.

Resources are saved into the Terraform state and can be referenced by other parts of a configuration. Resources are defined by a resource type/name, such as "example_thing", a schema representing the structure and data types of configuration, plan, and state, and lifecycle logic.

The main starting point for implementations in this package is the Resource type which represents an instance of a resource type that has its own configuration, plan, state, and lifecycle logic. A Resource is instantiated from a provider.ResourceType type NewResource method, which also defines the resource schema. The provider.ResourceType types are referenced by a provider.Provider type GetResources method, which enables the resource for practitioner and testing usage.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func ImportStatePassthroughID

func ImportStatePassthroughID(ctx context.Context, attrPath path.Path, req ImportStateRequest, resp *ImportStateResponse)

ImportStatePassthroughID is a helper function to set the import identifier to a given state attribute path. The attribute must accept a string value.

func RequiresReplace

func RequiresReplace() tfsdk.AttributePlanModifier

RequiresReplace returns an AttributePlanModifier specifying the attribute as requiring replacement. This behaviour is identical to the ForceNew behaviour in terraform-plugin-sdk and will result in the resource being destroyed and recreated when the following conditions are met:

1. The resource's state is not null; a null state indicates that we're creating a resource, and we never need to destroy and recreate a resource when we're creating it.

2. The resource's plan is not null; a null plan indicates that we're deleting a resource, and we never need to destroy and recreate a resource when we're deleting it.

3. The attribute's config is not null or the attribute is not computed; a computed attribute with a null config almost always means that the provider is changing the value, and practitioners are usually unpleasantly surprised when a resource is destroyed and recreated when their configuration hasn't changed. This has the unfortunate side effect that removing a computed field from the config will not trigger a destroy and recreate cycle, even when that is warranted. To get around this, provider developer can implement their own AttributePlanModifier that handles that behavior in the way that most makes sense for their use case.

4. The attribute's value in the plan does not match the attribute's value in the state.

func RequiresReplaceIf

func RequiresReplaceIf(f RequiresReplaceIfFunc, description, markdownDescription string) tfsdk.AttributePlanModifier

RequiresReplaceIf returns an AttributePlanModifier that mimics RequiresReplace, but only when the passed function `f` returns true. The resource will be destroyed and recreated if `f` returns true and the following conditions are met:

1. The resource's state is not null; a null state indicates that we're creating a resource, and we never need to destroy and recreate a resource when we're creating it.

2. The resource's plan is not null; a null plan indicates that we're deleting a resource, and we never need to destroy and recreate a resource when we're deleting it.

3. The attribute's config is not null or the attribute is not computed; a computed attribute with a null config almost always means that the provider is changing the value, and practitioners are usually unpleasantly surprised when a resource is destroyed and recreated when their configuration hasn't changed. This has the unfortunate side effect that removing a computed field from the config will not trigger a destroy and recreate cycle, even when that is warranted. To get around this, provider developer can implement their own AttributePlanModifier that handles that behavior in the way that most makes sense for their use case.

4. The attribute's value in the plan does not match the attribute's value in the state.

If `f` does not return true, RequiresReplaceIf will *not* override prior AttributePlanModifiers' determination of whether the resource needs to be recreated or not. This allows for multiple RequiresReplaceIf (or other modifiers that sometimes set RequiresReplace) to be used on a single attribute without the last one in the list always determining the outcome.

func UseStateForUnknown

func UseStateForUnknown() tfsdk.AttributePlanModifier

UseStateForUnknown returns an AttributePlanModifier that copies the prior state value for an attribute into that attribute's plan, if that state is non-null.

Computed attributes without the UseStateForUnknown attribute plan modifier will have their value set to Unknown in the plan by the framework to prevent Terraform errors, so their value always will be displayed as "(known after apply)" in the CLI plan output. Using this plan modifier will instead display the prior state value in the plan, unless a prior plan modifier adjusts the value.

Types

type ConfigValidator

type ConfigValidator interface {
	// Description describes the validation in plain text formatting.
	//
	// This information may be automatically added to resource plain text
	// descriptions by external tooling.
	Description(context.Context) string

	// MarkdownDescription describes the validation in Markdown formatting.
	//
	// This information may be automatically added to resource Markdown
	// descriptions by external tooling.
	MarkdownDescription(context.Context) string

	// ValidateResource performs the validation.
	//
	// This method name is separate from the datasource.ConfigValidator
	// interface ValidateDataSource method name and provider.ConfigValidator
	// interface ValidateProvider method name to allow generic validators.
	ValidateResource(context.Context, ValidateConfigRequest, *ValidateConfigResponse)
}

ConfigValidator describes reusable Resource configuration validation functionality.

type CreateRequest

type CreateRequest struct {
	// Config is the configuration the user supplied for the resource.
	//
	// This configuration may contain unknown values if a user uses
	// interpolation or other functionality that would prevent Terraform
	// from knowing the value at request time.
	Config tfsdk.Config

	// Plan is the planned state for the resource.
	Plan tfsdk.Plan

	// ProviderMeta is metadata from the provider_meta block of the module.
	ProviderMeta tfsdk.Config
}

CreateRequest represents a request for the provider to create a resource. An instance of this request struct is supplied as an argument to the resource's Create function.

type CreateResponse

type CreateResponse struct {
	// State is the state of the resource following the Create operation.
	// This field is pre-populated from CreateRequest.Plan and
	// should be set during the resource's Create operation.
	State tfsdk.State

	// Private is the private state resource data following the Create operation.
	// This field is not pre-populated as there is no pre-existing private state
	// data during the resource's Create operation.
	Private *privatestate.ProviderData

	// Diagnostics report errors or warnings related to creating the
	// resource. An empty slice indicates a successful operation with no
	// warnings or errors generated.
	Diagnostics diag.Diagnostics
}

CreateResponse represents a response to a CreateRequest. An instance of this response struct is supplied as an argument to the resource's Create function, in which the provider should set values on the CreateResponse as appropriate.

type DeleteRequest

type DeleteRequest struct {
	// State is the current state of the resource prior to the Delete
	// operation.
	State tfsdk.State

	// ProviderMeta is metadata from the provider_meta block of the module.
	ProviderMeta tfsdk.Config

	// Private is provider-defined resource private state data which was previously
	// stored with the resource state.
	//
	// Use the GetKey method to read data.
	Private *privatestate.ProviderData
}

DeleteRequest represents a request for the provider to delete a resource. An instance of this request struct is supplied as an argument to the resource's Delete function.

type DeleteResponse

type DeleteResponse struct {
	// State is the state of the resource following the Delete operation.
	// This field is pre-populated from UpdateResourceRequest.Plan and
	// should be set during the resource's Update operation.
	State tfsdk.State

	// Diagnostics report errors or warnings related to deleting the
	// resource. An empty slice indicates a successful operation with no
	// warnings or errors generated.
	Diagnostics diag.Diagnostics
}

DeleteResponse represents a response to a DeleteRequest. An instance of this response struct is supplied as an argument to the resource's Delete function, in which the provider should set values on the DeleteResponse as appropriate.

type ImportStateRequest

type ImportStateRequest struct {
	// ID represents the import identifier supplied by the practitioner when
	// calling the import command. In many cases, this may align with the
	// unique identifier for the resource, which can optionally be stored
	// as an Attribute. However, this identifier can also be treated as
	// its own type of value and parsed during import. This value
	// is not stored in the state unless the provider explicitly stores it.
	ID string
}

ImportStateRequest represents a request for the provider to import a resource. An instance of this request struct is supplied as an argument to the Resource's ImportState method.

type ImportStateResponse

type ImportStateResponse struct {
	// Diagnostics report errors or warnings related to importing the
	// resource. An empty slice indicates a successful operation with no
	// warnings or errors generated.
	Diagnostics diag.Diagnostics

	// State is the state of the resource following the import operation.
	// It must contain enough information so Terraform can successfully
	// refresh the resource, e.g. call the Resource Read method.
	State tfsdk.State

	// Private is the private state resource data following the Import operation.
	// This field is not pre-populated as there is no pre-existing private state
	// data during the resource's Import operation.
	Private *privatestate.ProviderData
}

ImportStateResponse represents a response to a ImportStateRequest. An instance of this response struct is supplied as an argument to the Resource's ImportState method, in which the provider should set values on the ImportStateResponse as appropriate.

type ModifyPlanRequest

type ModifyPlanRequest struct {
	// Config is the configuration the user supplied for the resource.
	//
	// This configuration may contain unknown values if a user uses
	// interpolation or other functionality that would prevent Terraform
	// from knowing the value at request time.
	Config tfsdk.Config

	// State is the current state of the resource.
	State tfsdk.State

	// Plan is the planned new state for the resource. Terraform 1.3 and later
	// supports resource destroy planning, in which this will contain a null
	// value.
	Plan tfsdk.Plan

	// ProviderMeta is metadata from the provider_meta block of the module.
	ProviderMeta tfsdk.Config

	// Private is provider-defined resource private state data which was previously
	// stored with the resource state. This data is opaque to Terraform and does
	// not affect plan output. Any existing data is copied to
	// ModifyPlanResponse.Private to prevent accidental private state data loss.
	//
	// Use the GetKey method to read data. Use the SetKey method on
	// ModifyPlanResponse.Private to update or remove a value.
	Private *privatestate.ProviderData
}

ModifyPlanRequest represents a request for the provider to modify the planned new state that Terraform has generated for the resource.

type ModifyPlanResponse

type ModifyPlanResponse struct {
	// Plan is the planned new state for the resource.
	Plan tfsdk.Plan

	// RequiresReplace is a list of attribute paths that require the
	// resource to be replaced. They should point to the specific field
	// that changed that requires the resource to be destroyed and
	// recreated.
	RequiresReplace path.Paths

	// Private is the private state resource data following the ModifyPlan operation.
	// This field is pre-populated from ModifyPlanRequest.Private and
	// can be modified during the resource's ModifyPlan operation.
	Private *privatestate.ProviderData

	// Diagnostics report errors or warnings related to determining the
	// planned state of the requested resource. Returning an empty slice
	// indicates a successful plan modification with no warnings or errors
	// generated.
	Diagnostics diag.Diagnostics
}

ModifyPlanResponse represents a response to a ModifyPlanRequest. An instance of this response struct is supplied as an argument to the resource's ModifyPlan function, in which the provider should modify the Plan and populate the RequiresReplace field as appropriate.

type ReadRequest

type ReadRequest struct {
	// State is the current state of the resource prior to the Read
	// operation.
	State tfsdk.State

	// Private is provider-defined resource private state data which was previously
	// stored with the resource state. This data is opaque to Terraform and does
	// not affect plan output. Any existing data is copied to
	// ReadResourceResponse.Private to prevent accidental private state data loss.
	//
	// Use the GetKey method to read data. Use the SetKey method on
	// ReadResourceResponse.Private to update or remove a value.
	Private *privatestate.ProviderData

	// ProviderMeta is metadata from the provider_meta block of the module.
	ProviderMeta tfsdk.Config
}

ReadRequest represents a request for the provider to read a resource, i.e., update values in state according to the real state of the resource. An instance of this request struct is supplied as an argument to the resource's Read function.

type ReadResponse

type ReadResponse struct {
	// State is the state of the resource following the Read operation.
	// This field is pre-populated from ReadRequest.State and
	// should be set during the resource's Read operation.
	State tfsdk.State

	// Private is the private state resource data following the Read operation.
	// This field is pre-populated from ReadResourceRequest.Private and
	// can be modified during the resource's Read operation.
	Private *privatestate.ProviderData

	// Diagnostics report errors or warnings related to reading the
	// resource. An empty slice indicates a successful operation with no
	// warnings or errors generated.
	Diagnostics diag.Diagnostics
}

ReadResponse represents a response to a ReadRequest. An instance of this response struct is supplied as an argument to the resource's Read function, in which the provider should set values on the ReadResponse as appropriate.

type RequiresReplaceIfFunc

type RequiresReplaceIfFunc func(ctx context.Context, state, config attr.Value, path path.Path) (bool, diag.Diagnostics)

RequiresReplaceIfFunc is a conditional function used in the RequiresReplaceIf plan modifier to determine whether the attribute requires replacement.

type Resource

type Resource interface {
	// Create is called when the provider must create a new resource. Config
	// and planned state values should be read from the
	// CreateRequest and new state values set on the CreateResponse.
	Create(context.Context, CreateRequest, *CreateResponse)

	// Read is called when the provider must read resource values in order
	// to update state. Planned state values should be read from the
	// ReadRequest and new state values set on the ReadResponse.
	Read(context.Context, ReadRequest, *ReadResponse)

	// Update is called to update the state of the resource. Config, planned
	// state, and prior state values should be read from the
	// UpdateRequest and new state values set on the UpdateResponse.
	Update(context.Context, UpdateRequest, *UpdateResponse)

	// Delete is called when the provider must delete the resource. Config
	// values may be read from the DeleteRequest.
	//
	// If execution completes without error, the framework will automatically
	// call DeleteResponse.State.RemoveResource(), so it can be omitted
	// from provider logic.
	Delete(context.Context, DeleteRequest, *DeleteResponse)
}

Resource represents an instance of a managed resource type. This is the core interface that all resources must implement.

Resources can optionally implement these additional concepts:

  • Import: ResourceWithImportState
  • Validation: Schema-based via tfsdk.Attribute or entire configuration via ResourceWithConfigValidators or ResourceWithValidateConfig.
  • Plan Modification: Schema-based via tfsdk.Attribute or entire plan via ResourceWithModifyPlan.
  • State Upgrades: ResourceWithUpgradeState

Although not required, it is conventional for resources to implement the ResourceWithImportState interface.

type ResourceWithConfigValidators

type ResourceWithConfigValidators interface {
	Resource

	// ConfigValidators returns a list of functions which will all be performed during validation.
	ConfigValidators(context.Context) []ConfigValidator
}

ResourceWithConfigValidators is an interface type that extends Resource to include declarative validations.

Declaring validation using this methodology simplifies implmentation of reusable functionality. These also include descriptions, which can be used for automating documentation.

Validation will include ConfigValidators and ValidateConfig, if both are implemented, in addition to any Attribute or Type validation.

type ResourceWithImportState

type ResourceWithImportState interface {
	Resource

	// ImportState is called when the provider must import the state of a
	// resource instance. This method must return enough state so the Read
	// method can properly refresh the full resource.
	//
	// If setting an attribute with the import identifier, it is recommended
	// to use the ImportStatePassthroughID() call in this method.
	ImportState(context.Context, ImportStateRequest, *ImportStateResponse)
}

Optional interface on top of Resource that enables provider control over the ImportResourceState RPC. This RPC is called by Terraform when the `terraform import` command is executed. Afterwards, the ReadResource RPC is executed to allow providers to fully populate the resource state.

type ResourceWithModifyPlan

type ResourceWithModifyPlan interface {
	Resource

	// ModifyPlan is called when the provider has an opportunity to modify
	// the plan: once during the plan phase when Terraform is determining
	// the diff that should be shown to the user for approval, and once
	// during the apply phase with any unknown values from configuration
	// filled in with their final values.
	//
	// The planned new state is represented by
	// ModifyPlanResponse.Plan. It must meet the following
	// constraints:
	// 1. Any non-Computed attribute set in config must preserve the exact
	// config value or return the corresponding attribute value from the
	// prior state (ModifyPlanRequest.State).
	// 2. Any attribute with a known value must not have its value changed
	// in subsequent calls to ModifyPlan or Create/Read/Update.
	// 3. Any attribute with an unknown value may either remain unknown
	// or take on any value of the expected type.
	//
	// Any errors will prevent further resource-level plan modifications.
	ModifyPlan(context.Context, ModifyPlanRequest, *ModifyPlanResponse)
}

ResourceWithModifyPlan represents a resource instance with a ModifyPlan function.

type ResourceWithUpgradeState

type ResourceWithUpgradeState interface {
	Resource

	// A mapping of prior state version to current schema version state upgrade
	// implementations. Only the specified state upgrader for the prior state
	// version is called, rather than each version in between, so it must
	// encapsulate all logic to convert the prior state to the current schema
	// version.
	//
	// Version keys begin at 0, which is the default schema version when
	// undefined. The framework will return an error diagnostic should the
	// requested state version not be implemented.
	UpgradeState(context.Context) map[int64]StateUpgrader
}

Optional interface on top of Resource that enables provider control over the UpgradeResourceState RPC. This RPC is automatically called by Terraform when the current Schema type Version field is greater than the stored state. Terraform does not store previous Schema information, so any breaking changes to state data types must be handled by providers.

Terraform CLI can execute the UpgradeResourceState RPC even when the prior state version matches the current schema version. The framework will automatically intercept this request and attempt to respond with the existing state. In this situation the framework will not execute any provider defined logic, so declaring it for this version is extraneous.

type ResourceWithValidateConfig

type ResourceWithValidateConfig interface {
	Resource

	// ValidateConfig performs the validation.
	ValidateConfig(context.Context, ValidateConfigRequest, *ValidateConfigResponse)
}

ResourceWithValidateConfig is an interface type that extends Resource to include imperative validation.

Declaring validation using this methodology simplifies one-off functionality that typically applies to a single resource. Any documentation of this functionality must be manually added into schema descriptions.

Validation will include ConfigValidators and ValidateConfig, if both are implemented, in addition to any Attribute or Type validation.

type StateUpgrader

type StateUpgrader struct {
	// Schema information for the prior state version. While not required,
	// setting this will populate the UpgradeStateRequest type State
	// field similar to other Resource data types. This allows for easier data
	// handling such as calling Get() or GetAttribute().
	//
	// If not set, prior state data is available in the
	// UpgradeResourceStateRequest type RawState field.
	PriorSchema *tfsdk.Schema

	// Provider defined logic for upgrading a resource state from the prior
	// state version to the current schema version.
	//
	// The context.Context parameter contains framework-defined loggers and
	// supports request cancellation.
	//
	// The UpgradeStateRequest parameter contains the prior state data.
	// If PriorSchema was set, the State field will be available. Otherwise,
	// the RawState must be used.
	//
	// The UpgradeStateResponse parameter should contain the upgraded
	// state data and can be used to signal any logic warnings or errors.
	StateUpgrader func(context.Context, UpgradeStateRequest, *UpgradeStateResponse)
}

Implementation handler for a UpgradeState operation.

This is used to encapsulate all upgrade logic from a prior state to the current schema version when a Resource implements the ResourceWithUpgradeState interface.

type UpdateRequest

type UpdateRequest struct {
	// Config is the configuration the user supplied for the resource.
	//
	// This configuration may contain unknown values if a user uses
	// interpolation or other functionality that would prevent Terraform
	// from knowing the value at request time.
	Config tfsdk.Config

	// Plan is the planned state for the resource.
	Plan tfsdk.Plan

	// State is the current state of the resource prior to the Update
	// operation.
	State tfsdk.State

	// ProviderMeta is metadata from the provider_meta block of the module.
	ProviderMeta tfsdk.Config

	// Private is provider-defined resource private state data which was previously
	// stored with the resource state. Any existing data is copied to
	// UpdateResponse.Private to prevent accidental private state data loss.
	//
	// Use the GetKey method to read data. Use the SetKey method on
	// UpdateResponse.Private to update or remove a value.
	Private *privatestate.ProviderData
}

UpdateRequest represents a request for the provider to update a resource. An instance of this request struct is supplied as an argument to the resource's Update function.

type UpdateResponse

type UpdateResponse struct {
	// State is the state of the resource following the Update operation.
	// This field is pre-populated from UpdateResourceRequest.Plan and
	// should be set during the resource's Update operation.
	State tfsdk.State

	// Private is the private state resource data following the Update operation.
	// This field is pre-populated from UpdateRequest.Private and
	// can be modified during the resource's Update operation.
	Private *privatestate.ProviderData

	// Diagnostics report errors or warnings related to updating the
	// resource. An empty slice indicates a successful operation with no
	// warnings or errors generated.
	Diagnostics diag.Diagnostics
}

UpdateResponse represents a response to an UpdateRequest. An instance of this response struct is supplied as an argument to the resource's Update function, in which the provider should set values on the UpdateResponse as appropriate.

type UpgradeStateRequest

type UpgradeStateRequest struct {
	// Previous state of the resource in JSON (Terraform CLI 0.12 and later)
	// or flatmap format, depending on which version of Terraform CLI last
	// wrote the resource state. This data is always available, regardless
	// whether the wrapping StateUpgrader type PriorSchema field was
	// present.
	//
	// This is advanced functionality for providers wanting to skip the full
	// redeclaration of older schemas and instead use lower level handlers to
	// transform data. A typical implementation for working with this data will
	// call the Unmarshal() method.
	//
	// TODO: Create framework defined type that is not protocol specific.
	// Reference: https://github.com/hashicorp/terraform-plugin-framework/issues/340
	RawState *tfprotov6.RawState

	// Previous state of the resource if the wrapping StateUpgrader
	// type PriorSchema field was present. When available, this allows for
	// easier data handling such as calling Get() or GetAttribute().
	State *tfsdk.State
}

Request information for the provider logic to update a resource state from a prior state version to the current schema version. An instance of this is supplied as a parameter to a StateUpgrader, which ultimately comes from a Resource's UpgradeState method.

type UpgradeStateResponse

type UpgradeStateResponse struct {
	// Diagnostics report errors or warnings related to upgrading the resource
	// state. An empty slice indicates a successful operation with no warnings
	// or errors generated.
	Diagnostics diag.Diagnostics

	// Upgraded state of the resource, which should match the current schema
	// version. If set, this will override State.
	//
	// This field is intended only for advanced provider functionality, such as
	// skipping the full redeclaration of older schemas or using lower level
	// handlers to transform data. Call tfprotov6.NewDynamicValue() to set this
	// value.
	//
	// All data must be populated to prevent data loss during the upgrade
	// operation. No prior state data is copied automatically.
	//
	// TODO: Remove in preference of requiring State, rather than using either
	// a new framework defined type or keeping this protocol specific type.
	// Reference: https://github.com/hashicorp/terraform-plugin-framework/issues/340
	DynamicValue *tfprotov6.DynamicValue

	// Upgraded state of the resource, which should match the current schema
	// version. If DynamicValue is set, it will override this value.
	//
	// This field allows for easier data handling such as calling Set() or
	// SetAttribute(). It is generally recommended over working with the lower
	// level types and functionality required for DynamicValue.
	//
	// All data must be populated to prevent data loss during the upgrade
	// operation. No prior state data is copied automatically.
	State tfsdk.State
}

Response information for the provider logic to update a resource state from a prior state version to the current schema version. An instance of this is supplied as a parameter to a StateUpgrader, which ultimately came from a Resource's UpgradeState method.

type ValidateConfigRequest

type ValidateConfigRequest struct {
	// Config is the configuration the user supplied for the resource.
	//
	// This configuration may contain unknown values if a user uses
	// interpolation or other functionality that would prevent Terraform
	// from knowing the value at request time.
	Config tfsdk.Config
}

ValidateConfigRequest represents a request to validate the configuration of a resource. An instance of this request struct is supplied as an argument to the Resource ValidateConfig receiver method or automatically passed through to each ConfigValidator.

type ValidateConfigResponse

type ValidateConfigResponse struct {
	// Diagnostics report errors or warnings related to validating the resource
	// configuration. An empty slice indicates success, with no warnings or
	// errors generated.
	Diagnostics diag.Diagnostics
}

ValidateConfigResponse represents a response to a ValidateConfigRequest. An instance of this response struct is supplied as an argument to the Resource ValidateConfig receiver method or automatically passed through to each ConfigValidator.

Jump to

Keyboard shortcuts

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