Terraform Azurerm 后端写入正常但无法读取

Terraform Azurerm backend writing ok but not reading

我正在尝试在 Azure 上设置一个简单的 Terraform 后端。我会写,但似乎阅读并没有真正起作用。例如,我尝试添加一个名为 test_aazurerm_resource_group,然后添加 terraform initterraform apply,它被正确存储在 Azure 上的存储桶中。

我修改了我的代码并更改了我的资源名称,将其命名为 test_b 然后是 terraform initterraform apply 并且 terraform 破坏了我的 test_a 并添加了我的 test_b 资源。 “Apply complete! Resources: 1 added, 0 changed, 1 destroyed.”。可能是什么问题?我可以看到,每当我执行 运行 我的 terraform init 命令时,它仍然会生成一个 .terraform 文件夹,里面有一个 terraform.tfstate

main.tf

terraform {
  required_providers {
    azurerm = {
      source  = "hashicorp/azurerm"
      version = "~>2.0"
    }
    azuread = {
      source  = "hashicorp/azuread"
      version = "~>1.0"
    }
  }
}

provider "azurerm" {
  features {}
}

resource "azurerm_resource_group" "test_a" {
  name     = "testing-resources"
  location = "West Europe"
}

backend_config.tf

terraform {
  required_version = ">= 0.12.6"
  
  backend "azurerm" {
    subscription_id      = "a095c3dd-xxx"
    resource_group_name  = "terraform"
    storage_account_name = "terraform963"
    container_name       = "tfstate"
    key                  = "terraform.tfstate"
  }
}

terraform.tfstate(存储在 Azure 中)

{
  "version": 4,
  "terraform_version": "0.14.3",
  "serial": 4,
  "lineage": "1fcb0f9a-7c26-xxx",
  "outputs": {},
  "resources": [
    {
      "mode": "managed",
      "type": "azurerm_resource_group",
      "name": "test_b",
      "provider": "provider[\"registry.terraform.io/hashicorp/azurerm\"]",
      "instances": [
        {
          "schema_version": 0,
          "attributes": {
            "id": "/subscriptions/a095c3dd-xxx/resourceGroups/testing-resources",
            "location": "westeurope",
            "name": "testing-resources",
            "tags": null,
            "timeouts": null
          },
          "sensitive_attributes": [],
          "private": "eyJlMmJmYjczxxx="
        }
      ]
    }
  ]
}

Terraform 使用此状态来创建计划并对您的基础架构进行更改。在任何操作之前,Terraform 会进行刷新以使用真实的基础设施更新状态。在这种情况下,您只需更改资源名称并保留现有的 resource_group 名称。 Terraform 将要求 import 将现有基础设施纳入状态。

Warning: Terraform expects that each remote object it is managing will be bound to only one resource address, which is normally guaranteed by Terraform itself having created all objects. If you import existing objects into Terraform, be careful to import each remote object to only one Terraform resource address.

您将使用命令 terraform import azurerm_resource_group.test_b <existingResourceGroupID> 导入状态。导入现有基础架构后,terraform 将尝试根据最新状态添加资源 azurerm_resource_group.test_b