Movatterモバイル変換


[0]ホーム

URL:


resource

package
v2.38.1Latest Latest
Warning

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

Go to latest
Published: Sep 22, 2025 License:MPL-2.0Imports:31Imported by:1,141

Details

Repository

github.com/hashicorp/terraform-plugin-sdk

Links

Documentation

Index

Examples

Constants

View Source
const (// Environment variable to enable acceptance tests using this package's// ParallelTest and Test functions whose TestCase does not enable the// IsUnitTest field. Defaults to disabled, in which each test will call// (*testing.T).Skip(). Can be set to any value to enable acceptance tests,// however "1" is conventional.EnvTfAcc = "TF_ACC"// Environment variable with hostname for the provider under acceptance// test. The hostname is the first portion of the full provider source// address, such as "example.com" in example.com/myorg/myprovider. Defaults// to "registry.terraform.io".//// Only required if any Terraform configuration set via the TestStep// type Config field includes a provider source, such as the terraform// configuration block required_providers attribute.EnvTfAccProviderHost = "TF_ACC_PROVIDER_HOST"// Environment variable with namespace for the provider under acceptance// test. The namespace is the second portion of the full provider source// address, such as "myorg" in registry.terraform.io/myorg/myprovider.// Defaults to "-" for Terraform 0.12-0.13 compatibility and "hashicorp".//// Only required if any Terraform configuration set via the TestStep// type Config field includes a provider source, such as the terraform// configuration block required_providers attribute.EnvTfAccProviderNamespace = "TF_ACC_PROVIDER_NAMESPACE")

Environment variables for acceptance testing. Additional environmentvariable constants can be found in the internal/plugintest package.

View Source
const TestEnvVar =EnvTfAcc

Deprecated: Use EnvTfAcc instead.

View Source
const UniqueIDSuffixLength =id.UniqueIDSuffixLength

Deprecated: Use helper/id package instead. This is required for migrating acceptancetesting to terraform-plugin-testing.

View Source
const UniqueIdPrefix =id.UniqueIdPrefix

Deprecated: Use helper/id package instead. This is required for migrating acceptancetesting to terraform-plugin-testing.

Variables

This section is empty.

Functions

funcAddTestSweepers

func AddTestSweepers(namestring, s *Sweeper)

AddTestSweepers function adds a given name and Sweeper configurationpair to the internal sweeperFuncs map. Invoke this function to register aresource sweeper to be available for running when the -sweep flag is usedwith `go test`. Sweeper names must be unique to help ensure a given sweeperis only ran once per run.

funcParallelTest

func ParallelTest(ttesting.T, cTestCase)

ParallelTest performs an acceptance test on a resource, allowing concurrencywith other ParallelTest. The number of concurrent tests is controlled by the"go test" command -parallel flag.

Tests will fail if they do not properly handle conditions to allow multipletests to occur against the same resource or service (e.g. random naming).

Test() function requirements and documentation also apply to this function.

funcPrefixedUniqueIddeprecated

func PrefixedUniqueId(prefixstring)string

Helper for a resource to generate a unique identifier w/ given prefix

After the prefix, the ID consists of an incrementing 26 digit value (to matchprevious timestamp output). After the prefix, the ID consists of a timestampand an incrementing 8 hex digit value The timestamp means that multiple IDscreated with the same prefix will sort in the order of their creation, evenacross multiple terraform executions, as long as the clock is not turned backbetween calls, and as long as any given terraform execution generates fewerthan 4 billion IDs.

Deprecated: Use helper/id package instead. This is required for migrating acceptancetesting to terraform-plugin-testing.

funcRetrydeprecated

func Retry(timeouttime.Duration, fRetryFunc)error

Retry is a basic wrapper around StateChangeConf that will just retrya function until it no longer returns an error.

Deprecated: Use helper/retry package instead. This is required for migrating acceptancetesting to terraform-plugin-testing.

funcRetryContextdeprecated

func RetryContext(ctxcontext.Context, timeouttime.Duration, fRetryFunc)error

RetryContext is a basic wrapper around StateChangeConf that will just retrya function until it no longer returns an error.

Cancellation from the passed in context will propagate through to theunderlying StateChangeConf

Deprecated: Use helper/retry package instead. This is required for migrating acceptancetesting to terraform-plugin-testing.

funcTest

func Test(ttesting.T, cTestCase)

Test performs an acceptance test on a resource.

Tests are not run unless an environmental variable "TF_ACC" isset to some non-empty value. This is to avoid test cases surprisinga user by creating real resources.

Tests will fail unless the verbose flag (`go test -v`, or explicitlythe "-test.v" flag) is set. Because some acceptance tests take quitelong, we require the verbose flag so users are able to see progressoutput.

Use the ParallelTest() function to automatically set (*testing.T).Parallel()to enable testing concurrency. Use the UnitTest() function to automaticallyset the TestCase type IsUnitTest field.

This function will automatically find or install Terraform CLI into atemporary directory, based on the following behavior:

  • If the TF_ACC_TERRAFORM_PATH environment variable is set, thatTerraform CLI binary is used if found and executable. If not found orexecutable, an error will be returned unless theTF_ACC_TERRAFORM_VERSION environment variable is also set.
  • If the TF_ACC_TERRAFORM_VERSION environment variable is set, installand use that Terraform CLI version.
  • If both the TF_ACC_TERRAFORM_PATH and TF_ACC_TERRAFORM_VERSIONenvironment variables are unset, perform a lookup for the TerraformCLI binary based on the operating system PATH. If not found, thelatest available Terraform CLI binary is installed.

Refer to the Env prefixed constants for additional details about theseenvironment variables, and others, that control testing functionality.

funcTestMain

func TestMain(m interface {Run()int})

TestMain adds sweeper functionality to the "go test" command, otherwisetests are executed as normal. Most provider acceptance tests are writtenusing the Test() function of this package, which imposes its ownrequirements and Terraform CLI behavior. Refer to that function'sdocumentation for additional details.

Sweepers enable infrastructure cleanup functions to be included withresource definitions, typically so developers can remove all resources ofthat resource type from testing infrastructure in case of failures thatprevented the normal resource destruction behavior of acceptance tests.Use the AddTestSweepers() function to configure available sweepers.

Sweeper flags added to the "go test" command:

-sweep: Comma-separated list of locations/regions to run available sweepers.-sweep-allow-failures: Enable to allow other sweepers to run after failures.-sweep-run: Comma-separated list of resource type sweepers to run. Defaults        to all sweepers.

Refer to the Env prefixed constants for environment variables that furthercontrol testing functionality.

funcUniqueIddeprecated

func UniqueId()string

Helper for a resource to generate a unique identifier w/ default prefix

Deprecated: Use helper/id package instead. This is required for migrating acceptancetesting to terraform-plugin-testing.

funcUnitTest

func UnitTest(ttesting.T, cTestCase)

UnitTest is a helper to force the acceptance testing harness to run in thenormal unit test suite. This should only be used for resource that don'thave any external dependencies.

Test() function requirements and documentation also apply to this function.

Types

typeCheckResourceAttrWithFuncadded inv2.15.0

type CheckResourceAttrWithFunc func(valuestring)error

CheckResourceAttrWithFunc is the callback type used to apply a custom checking logicwhen using TestCheckResourceAttrWith and a value is found for the given name and key.

When this function returns an error, TestCheckResourceAttrWith will fail the check.

typeErrorCheckFuncadded inv2.3.0

type ErrorCheckFunc func(error)error

ErrorCheckFunc is a function providers can use to handle errors.

typeExternalProvider

type ExternalProvider struct {VersionConstraintstring// the version constraint for the providerSourcestring// the provider source}

ExternalProvider holds information about third-party providers that shouldbe downloaded by Terraform as part of running the test step.

typeImportStateCheckFunc

type ImportStateCheckFunc func([]*terraform.InstanceState)error

ImportStateCheckFunc is the check function for ImportState tests

typeImportStateIdFunc

type ImportStateIdFunc func(*terraform.State) (string,error)

ImportStateIdFunc is an ID generation function to help with complex IDgeneration for ImportState tests.

typeNotFoundErrordeprecated

type NotFoundError =retry.NotFoundError

Deprecated: Use helper/retry package instead. This is required for migrating acceptancetesting to terraform-plugin-testing.

typeRetryErrordeprecated

type RetryError =retry.RetryError

RetryError is the required return type of RetryFunc. It forces client codeto choose whether or not a given error is retryable.

Deprecated: Use helper/retry package instead. This is required for migrating acceptancetesting to terraform-plugin-testing.

funcNonRetryableErrordeprecated

func NonRetryableError(errerror) *RetryError

NonRetryableError is a helper to create a RetryError that's _not_ retryablefrom a given error. To prevent logic errors, will return an error whenpassed a nil error.

Deprecated: Use helper/retry package instead. This is required for migrating acceptancetesting to terraform-plugin-testing.

funcRetryableErrordeprecated

func RetryableError(errerror) *RetryError

RetryableError is a helper to create a RetryError that's retryable from agiven error. To prevent logic errors, will return an error when passed anil error.

Deprecated: Use helper/retry package instead. This is required for migrating acceptancetesting to terraform-plugin-testing.

typeRetryFuncdeprecated

type RetryFunc =retry.RetryFunc

RetryFunc is the function retried until it succeeds.

Deprecated: Use helper/retry package instead. This is required for migrating acceptancetesting to terraform-plugin-testing.

typeStateChangeConfdeprecated

type StateChangeConf =retry.StateChangeConf

StateChangeConf is the configuration struct used for `WaitForState`.

Deprecated: Use helper/retry package instead. This is required for migrating acceptancetesting to terraform-plugin-testing.

typeStateRefreshFuncdeprecated

type StateRefreshFunc =retry.StateRefreshFunc

StateRefreshFunc is a function type used for StateChangeConf that isresponsible for refreshing the item being watched for a state change.

It returns three results. `result` is any object that will be returnedas the final object after waiting for state change. This allows you toreturn the final updated object, for example an EC2 instance after refreshingit. A nil result represents not found.

`state` is the latest state of that object. And `err` is any error thatmay have happened while refreshing the state.

Deprecated: Use helper/retry package instead. This is required for migrating acceptancetesting to terraform-plugin-testing.

typeSweeper

type Sweeper struct {// Name for sweeper. Must be unique to be ran by the Sweeper RunnerNamestring// Dependencies list the const names of other Sweeper functions that must be ran// prior to running this Sweeper. This is an ordered list that will be invoked// recursively at the helper/resource levelDependencies []string// Sweeper function that when invoked sweeps the Provider of specific// resourcesFSweeperFunc}

typeSweeperFunc

type SweeperFunc func(rstring)error

SweeperFunc is a signature for a function that acts as a sweeper. Itaccepts a string for the region that the sweeper is to be ran in. Thisfunction must be able to construct a valid client for that region.

typeTestCase

type TestCase struct {// IsUnitTest allows a test to run regardless of the TF_ACC// environment variable. This should be used with care - only for// fast tests on local resources (e.g. remote state with a local// backend) but can be used to increase confidence in correct// operation of Terraform without waiting for a full acctest run.IsUnitTestbool// PreCheck, if non-nil, will be called before any test steps are// executed. It will only be executed in the case that the steps// would run, so it can be used for some validation before running// acceptance tests, such as verifying that keys are setup.PreCheck func()// ProviderFactories can be specified for the providers that are valid.//// This can also be specified at the TestStep level to enable per-step// differences in providers, however all provider specifications must// be done either at the TestCase level or TestStep level, otherwise the// testing framework will raise an error and fail the test.//// These are the providers that can be referenced within the test. Each key// is an individually addressable provider. Typically you will only pass a// single value here for the provider you are testing. Aliases are not// supported by the test framework, so to use multiple provider instances,// you should add additional copies to this map with unique names. To set// their configuration, you would reference them similar to the following:////  provider "my_factory_key" {//    # ...//  }////  resource "my_resource" "mr" {//    provider = my_factory_key////    # ...//  }ProviderFactories map[string]func() (*schema.Provider,error)// ProtoV5ProviderFactories serves the same purpose as ProviderFactories,// but for protocol v5 providers defined using the terraform-plugin-go// ProviderServer interface.//// This can also be specified at the TestStep level to enable per-step// differences in providers, however all provider specifications must// be done either at the TestCase level or TestStep level, otherwise the// testing framework will raise an error and fail the test.ProtoV5ProviderFactories map[string]func() (tfprotov5.ProviderServer,error)// ProtoV6ProviderFactories serves the same purpose as ProviderFactories,// but for protocol v6 providers defined using the terraform-plugin-go// ProviderServer interface.// The version of Terraform used in acceptance testing must be greater// than or equal to v0.15.4 to use ProtoV6ProviderFactories.//// This can also be specified at the TestStep level to enable per-step// differences in providers, however all provider specifications must// be done either at the TestCase level or TestStep level, otherwise the// testing framework will raise an error and fail the test.ProtoV6ProviderFactories map[string]func() (tfprotov6.ProviderServer,error)// Providers is the ResourceProvider that will be under test.//// Deprecated: Providers is deprecated, please use ProviderFactoriesProviders map[string]*schema.Provider// ExternalProviders are providers the TestCase relies on that should// be downloaded from the registry during init.//// This can also be specified at the TestStep level to enable per-step// differences in providers, however all provider specifications must// be done either at the TestCase level or TestStep level, otherwise the// testing framework will raise an error and fail the test.//// This is generally unnecessary to set at the TestCase level, however// it has existing in the testing framework prior to the introduction of// TestStep level specification and was only necessary for performing// import testing where the configuration contained a provider outside the// one under test.ExternalProviders map[string]ExternalProvider// PreventPostDestroyRefresh can be set to true for cases where data sources// are tested alongside real resourcesPreventPostDestroyRefreshbool// CheckDestroy is called after the resource is finally destroyed// to allow the tester to test that the resource is truly gone.CheckDestroyTestCheckFunc// ErrorCheck allows providers the option to handle errors such as skipping// tests based on certain errors.ErrorCheckErrorCheckFunc// Steps are the apply sequences done within the context of the// same state. Each step can have its own check to verify correctness.Steps []TestStep// IDRefreshName is the name of the resource to check during ID-only// refresh testing, which ensures that a resource can be refreshed solely// by its identifier. This will default to the first non-nil primary// resource in the state. It runs every TestStep.//// While not deprecated, most resource tests should instead prefer using// TestStep.ImportState based testing as it works with multiple attribute// identifiers and also verifies resource import functionality.IDRefreshNamestring// IDRefreshIgnore is a list of configuration keys that will be ignored// during ID-only refresh testing.IDRefreshIgnore []string}

TestCase is a single acceptance test case used to test the apply/destroylifecycle of a resource in a specific configuration.

When the destroy plan is executed, the config from the last TestStepis used to plan it.

Refer to the Env prefixed constants for environment variables that furthercontrol testing functionality.

typeTestCheckFunc

type TestCheckFunc func(*terraform.State)error

TestCheckFunc is the callback type used with acceptance tests to checkthe state of a resource. The state passed in is the latest state known,or in the case of being after a destroy, it is the last known state whenit was created.

funcComposeAggregateTestCheckFunc

func ComposeAggregateTestCheckFunc(fs ...TestCheckFunc)TestCheckFunc

ComposeAggregateTestCheckFunc lets you compose multiple TestCheckFuncs intoa single TestCheckFunc.

As a user testing their provider, this lets you decompose your checksinto smaller pieces more easily.

Unlike ComposeTestCheckFunc, ComposeAggregateTestCheckFunc runs _all_ of theTestCheckFuncs and aggregates failures.

Example
package mainimport ("github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource")func main() {// This function is typically implemented in a TestStep type Check field.// Any TestCheckFunc and number of TestCheckFunc may be used within the// function parameters. Any errors are combined and displayed together.resource.ComposeAggregateTestCheckFunc(resource.TestCheckResourceAttr("example_thing.test", "example_attribute1", "one"),resource.TestCheckResourceAttr("example_thing.test", "example_attribute2", "two"),)}

funcComposeTestCheckFunc

func ComposeTestCheckFunc(fs ...TestCheckFunc)TestCheckFunc

ComposeTestCheckFunc lets you compose multiple TestCheckFuncs intoa single TestCheckFunc.

As a user testing their provider, this lets you decompose your checksinto smaller pieces more easily.

ComposeTestCheckFunc returns immediately on the first TestCheckFunc error.To aggregate all errors, use ComposeAggregateTestCheckFunc instead.

funcTestCheckModuleNoResourceAttr

func TestCheckModuleNoResourceAttr(mp []string, namestring, keystring)TestCheckFunc

TestCheckModuleNoResourceAttr - as per TestCheckNoResourceAttr but withsupport for non-root modules

funcTestCheckModuleResourceAttr

func TestCheckModuleResourceAttr(mp []string, namestring, keystring, valuestring)TestCheckFunc

TestCheckModuleResourceAttr - as per TestCheckResourceAttr but withsupport for non-root modules

funcTestCheckModuleResourceAttrPair

func TestCheckModuleResourceAttrPair(mpFirst []string, nameFirststring, keyFirststring, mpSecond []string, nameSecondstring, keySecondstring)TestCheckFunc

TestCheckModuleResourceAttrPair - as per TestCheckResourceAttrPair but withsupport for non-root modules

funcTestCheckModuleResourceAttrPtr

func TestCheckModuleResourceAttrPtr(mp []string, namestring, keystring, value *string)TestCheckFunc

TestCheckModuleResourceAttrPtr - as per TestCheckResourceAttrPtr but withsupport for non-root modules

funcTestCheckModuleResourceAttrSet

func TestCheckModuleResourceAttrSet(mp []string, namestring, keystring)TestCheckFunc

TestCheckModuleResourceAttrSet - as per TestCheckResourceAttrSet but withsupport for non-root modules

funcTestCheckNoResourceAttr

func TestCheckNoResourceAttr(name, keystring)TestCheckFunc

TestCheckNoResourceAttr ensures no value exists in the state for thegiven name and key combination. The opposite of this TestCheckFunc isTestCheckResourceAttrSet. State value checking is only recommended fortesting Computed attributes and attribute defaults.

For managed resources, the name parameter is combination of the resourcetype, a period (.), and the name label. The name for the below exampleconfiguration would be "myprovider_thing.example".

resource "myprovider_thing" "example" { ... }

For data sources, the name parameter is a combination of the keyword "data",a period (.), the data source type, a period (.), and the name label. Thename for the below example configuration would be"data.myprovider_thing.example".

data "myprovider_thing" "example" { ... }

The key parameter is an attribute path in Terraform CLI 0.11 and earlier"flatmap" syntax. Keys start with the attribute name of a top-levelattribute. Use the following special key syntax to inspect underlyingvalues of a list or map attribute:

  • .{NUMBER}: List value at index, e.g. .0 to inspect the first element.
  • .{KEY}: Map value at key, e.g. .example to inspect the example keyvalue.

While it is possible to check nested attributes under list and mapattributes using the special key syntax, checking a list, map, or setattribute directly is not supported. Use TestCheckResourceAttr withthe special .# or .% key syntax for those situations instead.

Example
package mainimport ("github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource")func main() {// This function is typically implemented in a TestStep type Check field,// wrapped with ComposeAggregateTestCheckFunc to combine results from// multiple checks.//// Given the following example configuration:////     resource "example_thing" "test" {//       example_string_attribute = "test-value"//     }//// The following TestCheckNoResourceAttr can be written to assert against// the expected state values.//// NOTE: State value checking is only necessary for Computed attributes,//       as the testing framework will automatically return test failures//       for configured attributes that mismatch the saved state, however//       this configuration and test is shown for illustrative purposes.resource.TestCheckNoResourceAttr("example_thing.test", "non_existent_attribute")}

funcTestCheckOutput

func TestCheckOutput(name, valuestring)TestCheckFunc

TestCheckOutput checks an output in the Terraform configuration

funcTestCheckResourceAttr

func TestCheckResourceAttr(name, key, valuestring)TestCheckFunc

TestCheckResourceAttr ensures a specific value is stored in state for thegiven name and key combination. State value checking is only recommended fortesting Computed attributes and attribute defaults.

For managed resources, the name parameter is combination of the resourcetype, a period (.), and the name label. The name for the below exampleconfiguration would be "myprovider_thing.example".

resource "myprovider_thing" "example" { ... }

For data sources, the name parameter is a combination of the keyword "data",a period (.), the data source type, a period (.), and the name label. Thename for the below example configuration would be"data.myprovider_thing.example".

data "myprovider_thing" "example" { ... }

The key parameter is an attribute path in Terraform CLI 0.11 and earlier"flatmap" syntax. Keys start with the attribute name of a top-levelattribute. Use the following special key syntax to inspect list, map, andset attributes:

  • .{NUMBER}: List value at index, e.g. .0 to inspect the first element.Use the TestCheckTypeSet* and TestMatchTypeSet* functions insteadfor sets.
  • .{KEY}: Map value at key, e.g. .example to inspect the example keyvalue.
  • .#: Number of elements in list or set.
  • .%: Number of elements in map.

The value parameter is the stringified data to check at the given key. Usethe following attribute type rules to set the value:

  • Boolean: "false" or "true".
  • Float/Integer: Stringified number, such as "1.2" or "123".
  • String: No conversion necessary.
Example (TypeBool)
package mainimport ("github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource")func main() {// This function is typically implemented in a TestStep type Check field,// wrapped with ComposeAggregateTestCheckFunc to combine results from// multiple checks.//// Given the following example configuration:////     resource "example_thing" "test" {//       example_bool_attribute = true//     }//// The following TestCheckResourceAttr can be written to assert against// the expected state values.//// NOTE: State value checking is only necessary for Computed attributes,//       as the testing framework will automatically return test failures//       for configured attributes that mismatch the saved state, however//       this configuration and test is shown for illustrative purposes.resource.TestCheckResourceAttr("example_thing.test", "example_bool_attribute", "true")}

Example (TypeFloat)
package mainimport ("github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource")func main() {// This function is typically implemented in a TestStep type Check field,// wrapped with ComposeAggregateTestCheckFunc to combine results from// multiple checks.//// Given the following example configuration:////     resource "example_thing" "test" {//       example_float_attribute = 1.2//     }//// The following TestCheckResourceAttr can be written to assert against// the expected state values.//// NOTE: State value checking is only necessary for Computed attributes,//       as the testing framework will automatically return test failures//       for configured attributes that mismatch the saved state, however//       this configuration and test is shown for illustrative purposes.resource.TestCheckResourceAttr("example_thing.test", "example_float_attribute", "1.2")}

Example (TypeInt)
package mainimport ("github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource")func main() {// This function is typically implemented in a TestStep type Check field,// wrapped with ComposeAggregateTestCheckFunc to combine results from// multiple checks.//// Given the following example configuration:////     resource "example_thing" "test" {//       example_int_attribute = 123//     }//// The following TestCheckResourceAttr can be written to assert against// the expected state values.//// NOTE: State value checking is only necessary for Computed attributes,//       as the testing framework will automatically return test failures//       for configured attributes that mismatch the saved state, however//       this configuration and test is shown for illustrative purposes.resource.TestCheckResourceAttr("example_thing.test", "example_int_attribute", "123")}

Example (TypeListAttribute)
package mainimport ("github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource")func main() {// This function is typically implemented in a TestStep type Check field,// wrapped with ComposeAggregateTestCheckFunc to combine results from// multiple checks.//// Given the following example configuration:////     resource "example_thing" "test" {//       example_list_attribute = ["value1", "value2", "value3"]//     }//// The following TestCheckResourceAttr can be written to assert against// the expected state values.//// NOTE: State value checking is only necessary for Computed attributes,//       as the testing framework will automatically return test failures//       for configured attributes that mismatch the saved state, however//       this configuration and test is shown for illustrative purposes.// Verify the list attribute contains 3 and only 3 elementsresource.TestCheckResourceAttr("example_thing.test", "example_list_attribute.#", "3")// Verify each list attribute element valueresource.TestCheckResourceAttr("example_thing.test", "example_list_attribute.0", "value1")resource.TestCheckResourceAttr("example_thing.test", "example_list_attribute.1", "value2")resource.TestCheckResourceAttr("example_thing.test", "example_list_attribute.2", "value3")}

Example (TypeListBlock)
package mainimport ("github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource")func main() {// This function is typically implemented in a TestStep type Check field,// wrapped with ComposeAggregateTestCheckFunc to combine results from// multiple checks.//// Given the following example configuration:////     resource "example_thing" "test" {//       example_list_block {//         example_string_attribute = "test-nested-value"//       }//     }//// The following TestCheckResourceAttr can be written to assert against// the expected state values.//// NOTE: State value checking is only necessary for Computed attributes,//       as the testing framework will automatically return test failures//       for configured attributes that mismatch the saved state, however//       this configuration and test is shown for illustrative purposes.// Verify the list block contains 1 and only 1 definitionresource.TestCheckResourceAttr("example_thing.test", "example_list_block.#", "1")// Verify a first list block attribute valueresource.TestCheckResourceAttr("example_thing.test", "example_list_block.0.example_string_attribute", "test-nested-value")}

Example (TypeMap)
package mainimport ("github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource")func main() {// This function is typically implemented in a TestStep type Check field,// wrapped with ComposeAggregateTestCheckFunc to combine results from// multiple checks.//// Given the following example configuration:////     resource "example_thing" "test" {//       example_map_attribute = {//         key1 = "value1"//         key2 = "value2"//         key3 = "value3"//       }//     }//// The following TestCheckResourceAttr can be written to assert against// the expected state values.//// NOTE: State value checking is only necessary for Computed attributes,//       as the testing framework will automatically return test failures//       for configured attributes that mismatch the saved state, however//       this configuration and test is shown for illustrative purposes.// Verify the map attribute contains 3 and only 3 elementsresource.TestCheckResourceAttr("example_thing.test", "example_map_attribute.%", "3")// Verify each map attribute element valueresource.TestCheckResourceAttr("example_thing.test", "example_map_attribute.key1", "value1")resource.TestCheckResourceAttr("example_thing.test", "example_map_attribute.key2", "value2")resource.TestCheckResourceAttr("example_thing.test", "example_map_attribute.key3", "value3")}

Example (TypeString)
package mainimport ("github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource")func main() {// This function is typically implemented in a TestStep type Check field,// wrapped with ComposeAggregateTestCheckFunc to combine results from// multiple checks.//// Given the following example configuration:////     resource "example_thing" "test" {//       example_string_attribute = "test-value"//     }//// The following TestCheckResourceAttr can be written to assert against// the expected state values.//// NOTE: State value checking is only necessary for Computed attributes,//       as the testing framework will automatically return test failures//       for configured attributes that mismatch the saved state, however//       this configuration and test is shown for illustrative purposes.resource.TestCheckResourceAttr("example_thing.test", "example_string_attribute", "test-value")}

funcTestCheckResourceAttrPair

func TestCheckResourceAttrPair(nameFirst, keyFirst, nameSecond, keySecondstring)TestCheckFunc

TestCheckResourceAttrPair ensures value equality in state between the firstgiven name and key combination and the second name and key combination.State value checking is only recommended for testing Computed attributesand attribute defaults.

For managed resources, the name parameter is combination of the resourcetype, a period (.), and the name label. The name for the below exampleconfiguration would be "myprovider_thing.example".

resource "myprovider_thing" "example" { ... }

For data sources, the name parameter is a combination of the keyword "data",a period (.), the data source type, a period (.), and the name label. Thename for the below example configuration would be"data.myprovider_thing.example".

data "myprovider_thing" "example" { ... }

The first and second names may use any combination of managed resourcesand/or data sources.

The key parameter is an attribute path in Terraform CLI 0.11 and earlier"flatmap" syntax. Keys start with the attribute name of a top-levelattribute. Use the following special key syntax to inspect list, map, andset attributes:

  • .{NUMBER}: List value at index, e.g. .0 to inspect the first element.Use the TestCheckTypeSet* and TestMatchTypeSet* functions insteadfor sets.
  • .{KEY}: Map value at key, e.g. .example to inspect the example keyvalue.
  • .#: Number of elements in list or set.
  • .%: Number of elements in map.
Example
package mainimport ("github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource")func main() {// This function is typically implemented in a TestStep type Check field,// wrapped with ComposeAggregateTestCheckFunc to combine results from// multiple checks.//// Given the following example configuration:////     resource "example_thing" "test1" {//       example_string_attribute = "test-value"//     }////     resource "example_thing" "test2" {//       example_string_attribute = example_thing.test1.example_string_attribute//     }//// The following TestCheckResourceAttrPair can be written to assert against// the expected state values.//// NOTE: State value checking is only necessary for Computed attributes,//       as the testing framework will automatically return test failures//       for configured attributes that mismatch the saved state, however//       this configuration and test is shown for illustrative purposes.resource.TestCheckResourceAttrPair("example_thing.test1","example_string_attribute","example_thing.test2","example_string_attribute",)}

funcTestCheckResourceAttrPtr

func TestCheckResourceAttrPtr(namestring, keystring, value *string)TestCheckFunc

TestCheckResourceAttrPtr is like TestCheckResourceAttr except thevalue is a pointer so that it can be updated while the test is running.It will only be dereferenced at the point this step is run.

Refer to the TestCheckResourceAttr documentation for more information aboutsetting the name, key, and value parameters.

funcTestCheckResourceAttrSet

func TestCheckResourceAttrSet(name, keystring)TestCheckFunc

TestCheckResourceAttrSet ensures any value exists in the state for thegiven name and key combination. The opposite of this TestCheckFunc isTestCheckNoResourceAttr. State value checking is only recommended fortesting Computed attributes and attribute defaults.

Use this as a last resort when a more specific TestCheckFunc cannot beimplemented, such as:

  • TestCheckResourceAttr: Equality checking of non-TypeSet state value.
  • TestCheckResourceAttrPair: Equality checking of non-TypeSet statevalue, based on another state value.
  • TestCheckTypeSet*: Equality checking of TypeSet state values.
  • TestMatchResourceAttr: Regular expression checking of non-TypeSetstate value.
  • TestMatchTypeSet*: Regular expression checking on TypeSet state values.

For managed resources, the name parameter is combination of the resourcetype, a period (.), and the name label. The name for the below exampleconfiguration would be "myprovider_thing.example".

resource "myprovider_thing" "example" { ... }

For data sources, the name parameter is a combination of the keyword "data",a period (.), the data source type, a period (.), and the name label. Thename for the below example configuration would be"data.myprovider_thing.example".

data "myprovider_thing" "example" { ... }

The key parameter is an attribute path in Terraform CLI 0.11 and earlier"flatmap" syntax. Keys start with the attribute name of a top-levelattribute. Use the following special key syntax to inspect underlyingvalues of a list or map attribute:

  • .{NUMBER}: List value at index, e.g. .0 to inspect the first element
  • .{KEY}: Map value at key, e.g. .example to inspect the example keyvalue

While it is possible to check nested attributes under list and mapattributes using the special key syntax, checking a list, map, or setattribute directly is not supported. Use TestCheckResourceAttr withthe special .# or .% key syntax for those situations instead.

Example
package mainimport ("github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource")func main() {// This function is typically implemented in a TestStep type Check field,// wrapped with ComposeAggregateTestCheckFunc to combine results from// multiple checks.//// Given the following example configuration:////     resource "example_thing" "test" {//       example_string_attribute = "test-value"//     }//// The following TestCheckResourceAttrSet can be written to assert against// the expected state values.//// NOTE: State value checking is only necessary for Computed attributes,//       as the testing framework will automatically return test failures//       for configured attributes that mismatch the saved state, however//       this configuration and test is shown for illustrative purposes.resource.TestCheckResourceAttrSet("example_thing.test", "example_string_attribute")}

funcTestCheckResourceAttrWithadded inv2.15.0

func TestCheckResourceAttrWith(name, keystring, checkValueFuncCheckResourceAttrWithFunc)TestCheckFunc

TestCheckResourceAttrWith ensures a value stored in state for thegiven name and key combination, is checked against a custom logic.State value checking is only recommended for testing Computed attributesand attribute defaults.

For managed resources, the name parameter is combination of the resourcetype, a period (.), and the name label. The name for the below exampleconfiguration would be "myprovider_thing.example".

resource "myprovider_thing" "example" { ... }

For data sources, the name parameter is a combination of the keyword "data",a period (.), the data source type, a period (.), and the name label. Thename for the below example configuration would be"data.myprovider_thing.example".

data "myprovider_thing" "example" { ... }

The key parameter is an attribute path in Terraform CLI 0.11 and earlier"flatmap" syntax. Keys start with the attribute name of a top-levelattribute. Use the following special key syntax to inspect list, map, andset attributes:

  • .{NUMBER}: List value at index, e.g. .0 to inspect the first element.Use the TestCheckTypeSet* and TestMatchTypeSet* functions insteadfor sets.
  • .{KEY}: Map value at key, e.g. .example to inspect the example keyvalue.
  • .#: Number of elements in list or set.
  • .%: Number of elements in map.

The checkValueFunc parameter is a CheckResourceAttrWithFunc,and it's provided with the attribute value to apply a custom checking logic,if it was found in the state. The function must return an error for thecheck to fail, or `nil` to succeed.

Example (TypeInt)
package mainimport ("fmt""strconv""github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource")func main() {// This function is typically implemented in a TestStep type Check field,// wrapped with ComposeAggregateTestCheckFunc to combine results from// multiple checks.//// Given the following example configuration:////     resource "example_thing" "test" {//       example_int_attribute = 10//     }//// The following TestCheckResourceAttrWith can be written to assert against// the expected state values.//// NOTE: State value checking is only necessary for Computed attributes,//       as the testing framework will automatically return test failures//       for configured attributes that mismatch the saved state, however//       this configuration and test is shown for illustrative purposes.// Verify the attribute value is an integer, and it's between 5 (included) and 20 (excluded)resource.TestCheckResourceAttrWith("example_thing.test", "example_string_attribute", func(value string) error {valueInt, err := strconv.Atoi(value)if err != nil {return err}if valueInt < 5 && valueInt >= 20 {return fmt.Errorf("should be between 5 and 20")}return nil})}

Example (TypeString)
package mainimport ("fmt""github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource")func main() {// This function is typically implemented in a TestStep type Check field,// wrapped with ComposeAggregateTestCheckFunc to combine results from// multiple checks.//// Given the following example configuration:////     resource "example_thing" "test" {//       example_string_attribute = "Very long string..."//     }//// The following TestCheckResourceAttrWith can be written to assert against// the expected state values.//// NOTE: State value checking is only necessary for Computed attributes,//       as the testing framework will automatically return test failures//       for configured attributes that mismatch the saved state, however//       this configuration and test is shown for illustrative purposes.// Verify the attribute value string length is above 1000resource.TestCheckResourceAttrWith("example_thing.test", "example_string_attribute", func(value string) error {if len(value) <= 1000 {return fmt.Errorf("should be longer than 1000 characters")}return nil})}

funcTestCheckTypeSetElemAttradded inv2.1.0

func TestCheckTypeSetElemAttr(name, attr, valuestring)TestCheckFunc

TestCheckTypeSetElemAttr ensures a specific value is stored in state for thegiven name and key combination under a list or set. Use this TestCheckFuncin preference over non-set variants to simplify testing code and ensurecompatibility with indices, which can easily change with schema changes.State value checking is only recommended for testing Computed attributes andattribute defaults.

For managed resources, the name parameter is a combination of the resourcetype, a period (.), and the name label. The name for the below exampleconfiguration would be "myprovider_thing.example".

resource "myprovider_thing" "example" { ... }

For data sources, the name parameter is a combination of the keyword "data",a period (.), the data source type, a period (.), and the name label. Thename for the below example configuration would be"data.myprovider_thing.example".

data "myprovider_thing" "example" { ... }

The key parameter is an attribute path in Terraform CLI 0.11 and earlier"flatmap" syntax. Keys start with the attribute name of a top-levelattribute. Use the sentinel value '*' to replace the element indexing intoa list or set. The sentinel value can be used for each list or set index, ifthere are multiple lists or sets in the attribute path.

The value parameter is the stringified data to check at the given key. Usethe following attribute type rules to set the value:

  • Boolean: "false" or "true".
  • Float/Integer: Stringified number, such as "1.2" or "123".
  • String: No conversion necessary.
Example
package mainimport ("github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource")func main() {// This function is typically implemented in a TestStep type Check field,// wrapped with ComposeAggregateTestCheckFunc to combine results from// multiple checks.//// Given the following example configuration:////     resource "example_thing" "test" {//       example_set_attribute = ["value1", "value2", "value3"]//     }//// The following TestCheckTypeSetElemAttr can be written to assert against// the expected state values.//// NOTE: State value checking is only necessary for Computed attributes,//       as the testing framework will automatically return test failures//       for configured attributes that mismatch the saved state, however//       this configuration and test is shown for illustrative purposes.resource.TestCheckTypeSetElemAttr("example_thing.test", "example_set_attribute.*", "value1")resource.TestCheckTypeSetElemAttr("example_thing.test", "example_set_attribute.*", "value2")resource.TestCheckTypeSetElemAttr("example_thing.test", "example_set_attribute.*", "value3")}

funcTestCheckTypeSetElemAttrPairadded inv2.1.0

func TestCheckTypeSetElemAttrPair(nameFirst, keyFirst, nameSecond, keySecondstring)TestCheckFunc

TestCheckTypeSetElemAttrPair ensures value equality in state between thefirst given name and key combination and the second name and keycombination. State value checking is only recommended for testing Computedattributes and attribute defaults.

For managed resources, the name parameter is a combination of the resourcetype, a period (.), and the name label. The name for the below exampleconfiguration would be "myprovider_thing.example".

resource "myprovider_thing" "example" { ... }

For data sources, the name parameter is a combination of the keyword "data",a period (.), the data source type, a period (.), and the name label. Thename for the below example configuration would be"data.myprovider_thing.example".

data "myprovider_thing" "example" { ... }

The first and second names may use any combination of managed resourcesand/or data sources.

The key parameter is an attribute path in Terraform CLI 0.11 and earlier"flatmap" syntax. Keys start with the attribute name of a top-levelattribute. Use the sentinel value '*' to replace the element indexing intoa list or set. The sentinel value can be used for each list or set index, ifthere are multiple lists or sets in the attribute path.

Example
package mainimport ("github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource")func main() {// This function is typically implemented in a TestStep type Check field,// wrapped with ComposeAggregateTestCheckFunc to combine results from// multiple checks.//// Given the following example configuration:////     data "example_lookup" "test" {//       example_string_attribute = "test-value"//     }////     resource "example_thing" "test" {//       example_set_attribute = [//         data.example_lookup.test.example_string_attribute,//         "another-test-value",//       ]//     }//// The following TestCheckTypeSetElemAttrPair can be written to assert// against the expected state values.//// NOTE: State value checking is only necessary for Computed attributes,//       as the testing framework will automatically return test failures//       for configured attributes that mismatch the saved state, however//       this configuration and test is shown for illustrative purposes.resource.TestCheckTypeSetElemAttrPair("example_thing.test","example_set_attribute.*","data.example_lookup.test","example_string_attribute",)}

funcTestCheckTypeSetElemNestedAttrsadded inv2.1.0

func TestCheckTypeSetElemNestedAttrs(name, attrstring, values map[string]string)TestCheckFunc

TestCheckTypeSetElemNestedAttrs ensures a subset map of values is stored instate for the given name and key combination of attributes nested under alist or set block. Use this TestCheckFunc in preference over non-setvariants to simplify testing code and ensure compatibility with indices,which can easily change with schema changes. State value checking is onlyrecommended for testing Computed attributes and attribute defaults.

For managed resources, the name parameter is a combination of the resourcetype, a period (.), and the name label. The name for the below exampleconfiguration would be "myprovider_thing.example".

resource "myprovider_thing" "example" { ... }

For data sources, the name parameter is a combination of the keyword "data",a period (.), the data source type, a period (.), and the name label. Thename for the below example configuration would be"data.myprovider_thing.example".

data "myprovider_thing" "example" { ... }

The key parameter is an attribute path in Terraform CLI 0.11 and earlier"flatmap" syntax. Keys start with the attribute name of a top-levelattribute. Use the sentinel value '*' to replace the element indexing intoa list or set. The sentinel value can be used for each list or set index, ifthere are multiple lists or sets in the attribute path.

The values parameter is the map of attribute names to attribute valuesexpected to be nested under the list or set.

You may check for unset nested attributes, however this will also match keysset to an empty string. Use a map with at least 1 non-empty value.

map[string]string{  "key1": "value",  "key2": "",}

If the values map is not granular enough, it is possible to match an elementyou were not intending to in the set. Provide the most complete mapping ofattributes possible to be sure the unique element exists.

Example
package mainimport ("github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource")func main() {// This function is typically implemented in a TestStep type Check field,// wrapped with ComposeAggregateTestCheckFunc to combine results from// multiple checks.//// Given the following example configuration:////     resource "example_thing" "test" {//       example_set_block {//         key1 = "value1a"//         key2 = "value2a"//         key3 = "value3a"//       }////       example_set_block {//         key1 = "value1b"//         key2 = "value2b"//         key3 = "value3b"//       }//     }//// The following TestCheckTypeSetElemNestedAttrs can be written to assert// against the expected state values.//// NOTE: State value checking is only necessary for Computed attributes,//       as the testing framework will automatically return test failures//       for configured attributes that mismatch the saved state, however//       this configuration and test is shown for illustrative purposes.resource.TestCheckTypeSetElemNestedAttrs("example_thing.test","example_set_block.*",map[string]string{"key1": "value1a","key2": "value2a","key3": "value3a",},)resource.TestCheckTypeSetElemNestedAttrs("example_thing.test","example_set_block.*",map[string]string{"key1": "value1b","key2": "value2b","key3": "value3b",},)}

funcTestMatchOutput

func TestMatchOutput(namestring, r *regexp.Regexp)TestCheckFunc

funcTestMatchResourceAttr

func TestMatchResourceAttr(name, keystring, r *regexp.Regexp)TestCheckFunc

TestMatchResourceAttr ensures a value matching a regular expression isstored in state for the given name and key combination. State value checkingis only recommended for testing Computed attributes and attribute defaults.

For managed resources, the name parameter is combination of the resourcetype, a period (.), and the name label. The name for the below exampleconfiguration would be "myprovider_thing.example".

resource "myprovider_thing" "example" { ... }

For data sources, the name parameter is a combination of the keyword "data",a period (.), the data source type, a period (.), and the name label. Thename for the below example configuration would be"data.myprovider_thing.example".

data "myprovider_thing" "example" { ... }

The key parameter is an attribute path in Terraform CLI 0.11 and earlier"flatmap" syntax. Keys start with the attribute name of a top-levelattribute. Use the following special key syntax to inspect list, map, andset attributes:

  • .{NUMBER}: List value at index, e.g. .0 to inspect the first element.Use the TestCheckTypeSet* and TestMatchTypeSet* functions insteadfor sets.
  • .{KEY}: Map value at key, e.g. .example to inspect the example keyvalue.
  • .#: Number of elements in list or set.
  • .%: Number of elements in map.

The value parameter is a compiled regular expression. A typical pattern isusing the regexp.MustCompile() function, which will automatically ensure theregular expression is supported by the Go regular expression handlers duringcompilation.

Example
package mainimport ("regexp""github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource")func main() {// This function is typically implemented in a TestStep type Check field,// wrapped with ComposeAggregateTestCheckFunc to combine results from// multiple checks.//// Given the following example configuration:////     resource "example_thing" "test" {//       example_string_attribute = "test-value"//     }//// The following TestMatchResourceAttr can be written to assert against// the expected state values.//// NOTE: State value checking is only necessary for Computed attributes,//       as the testing framework will automatically return test failures//       for configured attributes that mismatch the saved state, however//       this configuration and test is shown for illustrative purposes.resource.TestMatchResourceAttr("example_thing.test", "example_string_attribute", regexp.MustCompile(`^test-`))}

funcTestMatchTypeSetElemNestedAttrsadded inv2.1.0

func TestMatchTypeSetElemNestedAttrs(name, attrstring, values map[string]*regexp.Regexp)TestCheckFunc

TestMatchTypeSetElemNestedAttrs ensures a subset map of values, compared byregular expressions, is stored in state for the given name and keycombination of attributes nested under a list or set block. Use thisTestCheckFunc in preference over non-set variants to simplify testing codeand ensure compatibility with indices, which can easily change with schemachanges. State value checking is only recommended for testing Computedattributes and attribute defaults.

For managed resources, the name parameter is a combination of the resourcetype, a period (.), and the name label. The name for the below exampleconfiguration would be "myprovider_thing.example".

resource "myprovider_thing" "example" { ... }

For data sources, the name parameter is a combination of the keyword "data",a period (.), the data source type, a period (.), and the name label. Thename for the below example configuration would be"data.myprovider_thing.example".

data "myprovider_thing" "example" { ... }

The key parameter is an attribute path in Terraform CLI 0.11 and earlier"flatmap" syntax. Keys start with the attribute name of a top-levelattribute. Use the sentinel value '*' to replace the element indexing intoa list or set. The sentinel value can be used for each list or set index, ifthere are multiple lists or sets in the attribute path.

The values parameter is the map of attribute names to regular expressionsfor matching attribute values expected to be nested under the list or set.

You may check for unset nested attributes, however this will also match keysset to an empty string. Use a map with at least 1 non-empty value.

map[string]*regexp.Regexp{  "key1": regexp.MustCompile(`^value`),  "key2": regexp.MustCompile(`^$`),}

If the values map is not granular enough, it is possible to match an elementyou were not intending to in the set. Provide the most complete mapping ofattributes possible to be sure the unique element exists.

Example
package mainimport ("regexp""github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource")func main() {// This function is typically implemented in a TestStep type Check field,// wrapped with ComposeAggregateTestCheckFunc to combine results from// multiple checks.//// Given the following example configuration:////     resource "example_thing" "test" {//       example_set_block {//         key1 = "value1a"//         key2 = "value2a"//         key3 = "value3a"//       }////       example_set_block {//         key1 = "value1b"//         key2 = "value2b"//         key3 = "value3b"//       }//     }//// The following TestMatchTypeSetElemNestedAttrs can be written to assert// against the expected state values.//// NOTE: State value checking is only necessary for Computed attributes,//       as the testing framework will automatically return test failures//       for configured attributes that mismatch the saved state, however//       this configuration and test is shown for illustrative purposes.resource.TestMatchTypeSetElemNestedAttrs("example_thing.test","example_set_block.*",map[string]*regexp.Regexp{"key1": regexp.MustCompile(`1a$`),"key2": regexp.MustCompile(`2a$`),"key3": regexp.MustCompile(`3a$`),},)resource.TestMatchTypeSetElemNestedAttrs("example_thing.test","example_set_block.*",map[string]*regexp.Regexp{"key1": regexp.MustCompile(`1b$`),"key2": regexp.MustCompile(`2b$`),"key3": regexp.MustCompile(`3b$`),},)}

funcTestModuleMatchResourceAttr

func TestModuleMatchResourceAttr(mp []string, namestring, keystring, r *regexp.Regexp)TestCheckFunc

TestModuleMatchResourceAttr - as per TestMatchResourceAttr but withsupport for non-root modules

typeTestStep

type TestStep struct {// ResourceName should be set to the name of the resource// that is being tested. Example: "aws_instance.foo". Various test// modes use this to auto-detect state information.//// This is only required if the test mode settings below say it is// for the mode you're using.ResourceNamestring// PreConfig is called before the Config is applied to perform any per-step// setup that needs to happen. This is called regardless of "test mode"// below.PreConfig func()// Taint is a list of resource addresses to taint prior to the execution of// the step. Be sure to only include this at a step where the referenced// address will be present in state, as it will fail the test if the resource// is missing.//// This option is ignored on ImportState tests, and currently only works for// resources in the root module path.Taint []string// Config a string of the configuration to give to Terraform. If this// is set, then the TestCase will execute this step with the same logic// as a `terraform apply`.//// JSON Configuration Syntax can be used and is assumed whenever Config// contains valid JSON.Configstring// Check is called after the Config is applied. Use this step to// make your own API calls to check the status of things, and to// inspect the format of the ResourceState itself.//// If an error is returned, the test will fail. In this case, a// destroy plan will still be attempted.//// If this is nil, no check is done on this step.CheckTestCheckFunc// Destroy will create a destroy plan if set to true.Destroybool// ExpectNonEmptyPlan can be set to true for specific types of tests that are// looking to verify that a diff occursExpectNonEmptyPlanbool// ExpectError allows the construction of test cases that we expect to fail// with an error. The specified regexp must match against the error for the// test to pass.ExpectError *regexp.Regexp// PlanOnly can be set to only run `plan` with this configuration, and not// actually apply it. This is useful for ensuring config changes result in// no-op plansPlanOnlybool// PreventDiskCleanup can be set to true for testing terraform modules which// require access to disk at runtime. Note that this will leave files in the// temp folderPreventDiskCleanupbool// PreventPostDestroyRefresh can be set to true for cases where data sources// are tested alongside real resourcesPreventPostDestroyRefreshbool// SkipFunc enables skipping the TestStep, based on environment criteria.// For example, this can prevent running certain steps that may be runtime// platform or API configuration dependent.//// Return true with no error to skip the test step. The error return// should be used to signify issues that prevented the function from// completing as expected.//// SkipFunc is called after PreConfig but before applying the Config.SkipFunc func() (bool,error)// ImportState, if true, will test the functionality of ImportState// by importing the resource with ResourceName (must be set) and the// ID of that resource.ImportStatebool// ImportStateId is the ID to perform an ImportState operation with.// This is optional. If it isn't set, then the resource ID is automatically// determined by inspecting the state for ResourceName's ID.ImportStateIdstring// ImportStateIdPrefix is the prefix added in front of ImportStateId.// This can be useful in complex import cases, where more than one// attribute needs to be passed on as the Import ID. Mainly in cases// where the ID is not known, and a known prefix needs to be added to// the unset ImportStateId field.ImportStateIdPrefixstring// ImportStateIdFunc is a function that can be used to dynamically generate// the ID for the ImportState tests. It is sent the state, which can be// checked to derive the attributes necessary and generate the string in the// desired format.ImportStateIdFuncImportStateIdFunc// ImportStateCheck checks the results of ImportState. It should be// used to verify that the resulting value of ImportState has the// proper resources, IDs, and attributes.//// Prefer ImportStateVerify over ImportStateCheck, unless the resource// import explicitly is expected to create multiple resources (not a// recommended resource implementation) or if attributes are imported with// syntactically different but semantically/functionally equivalent values// where special logic is needed.//// Terraform versions 1.3 and later can include data source states during// import, which the testing framework will skip to prevent the need for// Terraform version specific logic in provider testing.ImportStateCheckImportStateCheckFunc// ImportStateVerify, if true, will also check that the state values// that are finally put into the state after import match for all the// IDs returned by the Import.  Note that this checks for strict equality// and does not respect DiffSuppressFunc or CustomizeDiff.//// ImportStateVerifyIgnore is a list of prefixes of fields that should// not be verified to be equal. These can be set to ephemeral fields or// fields that can't be refreshed and don't matter.ImportStateVerifyboolImportStateVerifyIgnore []string// ImportStatePersist, if true, will update the persisted state with the// state generated by the import operation (i.e., terraform import). When// false (default) the state generated by the import operation is discarded// at the end of the test step that is verifying import behavior.ImportStatePersistbool// RefreshState, if true, will test the functionality of `terraform// refresh` by refreshing the state, running any checks against the// refreshed state, and running a plan to verify against unexpected plan// differences.//// If the refresh is expected to result in a non-empty plan// ExpectNonEmptyPlan should be set to true in the same TestStep.//// RefreshState cannot be the first TestStep and, it is mutually exclusive// with ImportState.RefreshStatebool// ProviderFactories can be specified for the providers that are valid for// this TestStep. When providers are specified at the TestStep level, all// TestStep within a TestCase must declare providers.//// This can also be specified at the TestCase level for all TestStep,// however all provider specifications must be done either at the TestCase// level or TestStep level, otherwise the testing framework will raise an// error and fail the test.//// These are the providers that can be referenced within the test. Each key// is an individually addressable provider. Typically you will only pass a// single value here for the provider you are testing. Aliases are not// supported by the test framework, so to use multiple provider instances,// you should add additional copies to this map with unique names. To set// their configuration, you would reference them similar to the following:////  provider "my_factory_key" {//    # ...//  }////  resource "my_resource" "mr" {//    provider = my_factory_key////    # ...//  }ProviderFactories map[string]func() (*schema.Provider,error)// ProtoV5ProviderFactories serves the same purpose as ProviderFactories,// but for protocol v5 providers defined using the terraform-plugin-go// ProviderServer interface. When providers are specified at the TestStep// level, all TestStep within a TestCase must declare providers.//// This can also be specified at the TestCase level for all TestStep,// however all provider specifications must be done either at the TestCase// level or TestStep level, otherwise the testing framework will raise an// error and fail the test.ProtoV5ProviderFactories map[string]func() (tfprotov5.ProviderServer,error)// ProtoV6ProviderFactories serves the same purpose as ProviderFactories,// but for protocol v6 providers defined using the terraform-plugin-go// ProviderServer interface.// The version of Terraform used in acceptance testing must be greater// than or equal to v0.15.4 to use ProtoV6ProviderFactories. When providers// are specified at the TestStep level, all TestStep within a TestCase must// declare providers.//// This can also be specified at the TestCase level for all TestStep,// however all provider specifications must be done either at the TestCase// level or TestStep level, otherwise the testing framework will raise an// error and fail the test.ProtoV6ProviderFactories map[string]func() (tfprotov6.ProviderServer,error)// ExternalProviders are providers the TestStep relies on that should// be downloaded from the registry during init. When providers are// specified at the TestStep level, all TestStep within a TestCase must// declare providers.//// This can also be specified at the TestCase level for all TestStep,// however all provider specifications must be done either at the TestCase// level or TestStep level, otherwise the testing framework will raise an// error and fail the test.//// Outside specifying an earlier version of the provider under test,// typically for state upgrader testing, this is generally only necessary// for performing import testing where the prior TestStep configuration// contained a provider outside the one under test.ExternalProviders map[string]ExternalProvider}

TestStep is a single apply sequence of a test, done within thecontext of a state.

Multiple TestSteps can be sequenced in a Test to allow testingpotentially complex update logic. In general, simply create/destroytests will only need one step.

Refer to the Env prefixed constants for environment variables that furthercontrol testing functionality.

typeTimeoutErrordeprecated

type TimeoutError =retry.TimeoutError

TimeoutError is returned when WaitForState times out

Deprecated: Use helper/retry package instead. This is required for migrating acceptancetesting to terraform-plugin-testing.

typeUnexpectedStateErrordeprecated

type UnexpectedStateError =retry.UnexpectedStateError

UnexpectedStateError is returned when Refresh returns a state that's neither in Target nor Pending

Deprecated: Use helper/retry package instead. This is required for migrating acceptancetesting to terraform-plugin-testing.

Source Files

View all Source files

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f orF : Jump to
y orY : Canonical URL
go.dev uses cookies from Google to deliver and enhance the quality of its services and to analyze traffic.Learn more.

[8]ページ先頭

©2009-2025 Movatter.jp