hashicorp / hashicorp/terraform-plugin-testing

Allow easier testing of resource's disappearance

Open
#73 4 comments 4 reactions 0 assignees View on GitHub
enhancement
Dominant language
Go
Stars
68
Forks
22
Avg merge
2d 12h
Merged PRs (30d)
1

Description

## Problem statement

It is a convention for Terraform to _not_ error out when a resource was deleted out of bound (e.g. by hand or another tooling outside of Terraform) and instead wipe it out of the state and automatically plan its recreation.

For this to work though each provider has to implement such behaviour correctly for each resource and this is not trivial nor easy to implement today.

The common pattern to achieve this is:

1. Add a condition to `Read` which calls `d.SetId("")` (i.e. remove resource from state) if resource is not found via API (e.g. when API returns 404 error) and issue `WARN` log message in such case. This could/should be a user-visible warning, but that requires https://github.com/hashicorp/terraform-plugin-sdk/issues/230
2. Add acceptance test which deletes the resource via API - without calling `Delete` explicitly, to simulate the failure mode and has `ExpectNonEmptyPlan: true`. Any acceptance tests generally expects all operations to _not_ error.

### Example

https://github.com/terraform-providers/terraform-provider-aws/blob/master/aws/resource_aws_cloudwatch_log_stream.go#L73-L77

```go
if !exists {
log.Printf("[DEBUG] CloudWatch Stream %q Not Found. Removing from state", d.Id())
d.SetId("")
return nil
}
```

https://github.com/terraform-providers/terraform-provider-aws/blob/f39af7fff691603f5dc5b553c618d1dbdb6ea0df/aws/resource_aws_cloudwatch_log_stream_test.go#L33-L52

```go
func TestAccAWSCloudWatchLogStream_disappears(t *testing.T) {
var ls cloudwatchlogs.LogStream
rName := acctest.RandString(15)

resource.ParallelTest(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders,
CheckDestroy: testAccCheckAWSCloudWatchLogStreamDestroy,
Steps: []resource.TestStep{
{
Config: testAccAWSCloudWatchLogStreamConfig(rName),
Check: resource.ComposeTestCheckFunc(
testAccCheckCloudWatchLogStreamExists("aws_cloudwatch_log_stream.foobar", &ls),
testAccCheckCloudWatchLogStreamDisappears(&ls, rName),
),
ExpectNonEmptyPlan: true,
},
},
})
}
```

## Proposal

Exact implementation is TBD, but it would be great to come up with something as simple as a flag for `resource.TestStep` which automatically tests these scenarios, so that more provider developers get into the habit of testing this more regularly and we _really_ make this a widely accepted convention in providers.

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.