0

我正在构建一个 Terraform 模块来使用 AWS S3 和 AWS DynamoDB 创建一个 Terraform 远程后端,并希望避免通过terraform destroy. 因此,我使用此解决方法lifecycle { prevent_destroy = true }申请我的模块的资源:

resource "random_id" "protector" {
  count       = var.prevent_destroy ? 1 : 0
  byte_length = 16

  keepers = {
    s3_bucket_id      = aws_s3_bucket.this.id
    dynamodb_table_id = aws_dynamodb_table.this.id
  }

  lifecycle {
    prevent_destroy = true
  }
}

接下来,我想通过调用来测试资源是否不会被破坏,terraform destroy以确保我的模块按预期工作。Terratest正如 Yevgeniy Brikman 在Terraform: Up and Running中解释的那样,我使用库创建了一个测试:

package test

import (
    "testing"
    "github.com/gruntwork-io/terratest/modules/terraform"
)

func TestIndestructibleS3BackendCreateAndFailedDestroy(t *testing.T) {
    opts := &terraform.Options{
        // pass the example's directory
        TerraformDir: "../examples/terraform-s3-backend/indestructible-backend",
    }

    // TODO defer removeProtectorAndDestroy

    terraform.InitAndApply(t, opts)
    terraform.Destroy(t, opts) // we want this call to fail
    
    // TODO catch exception and check that it indicates that the resources cannot be deleted
    
}

正如预期的那样,测试失败了:

TestIndestructibleS3BackendCreateAndFailedDestroy 2021-06-28T14:06:24+02:00 retry.go:99: Returning due to fatal error: FatalError{Underlying: error while running command: exit status 1; ╷
│ Error: Instance cannot be destroyed
│ 
│   on ../../../modules/terraform-s3-backend/main.tf line 44:
│   44: resource "random_id" "protector" {
│ 
│ Resource module.example-s3-backend.random_id.protector[0] has
│ lifecycle.prevent_destroy set, but the plan calls for this resource to be
│ destroyed. To avoid this error and continue with the plan, either disable
│ lifecycle.prevent_destroy or reduce the scope of the plan using the -target
│ flag.
╵}

我如何断言在天真的调用之后引发了错误terraform.Destroy?另外,我怎样才能在这个测试后正确清理?我想删除保护器并在之后销毁资源。

4

0 回答 0