terraform-plugin-sdk
terraform-plugin-sdk copied to clipboard
Add exported function to retrieve attribute from state for use during tests
SDK version
v2.20.0
Use-cases
Occasionally, when writing acceptance tests it is useful to be able to extract and store a value from state in order to use in subsequent test steps. For instance, when using the Taint field in a TestStep it is useful to be able to verify that a resource has been destroyed and recreated.
Attempted Solutions
Adding a function along the following lines to each provider which needs to be able to compare attributes before and after test steps.
func testExtractResourceAttr(resourceName string, attributeName string, attributeValue *string) r.TestCheckFunc {
return func(s *terraform.State) error {
rs, ok := s.RootModule().Resources[resourceName]
if !ok {
return fmt.Errorf("resource name %s not found in state", resourceName)
}
attrValue, ok := rs.Primary.Attributes[attributeName]
if !ok {
return fmt.Errorf("attribute %s not found in resource %s state", attributeName, resourceName)
}
*attributeValue = attrValue
return nil
}
}
Proposal
Add an exported function to /helper/resource that exposes this functionality to avoid code duplication in providers.
References
We've certainly seen providers that use this class of attribute value extraction across TestStep. 😄 I'm wondering if its worth investigating this enhancement against the context of these as well:
- https://github.com/hashicorp/terraform-plugin-sdk/issues/77
- https://github.com/hashicorp/terraform-plugin-sdk/issues/236
- https://github.com/hashicorp/terraform-plugin-sdk/issues/482
They're all circling around verifying the resource under test was planned for and/or deleted/recreated properly. More easily enabling provider developers to extract values and perform their own equivalence testing certainly is interesting.