获取 Terraform 资源已经存在错误,资源刚刚由 Terraform 创建

Getting Terraform resource already exists error with resource just created by Terraform

我正在使用 Terraform 在 Azure 中设置虚拟网络。

我有几个 VNet,每个都有自己的网络安全组 100% 在 Terraform 中管理,在 运行ning Terraform 之前,除了资源组之外没有其他资源。

当我运行Terraform apply第一次正确创建所有资源。但是,如果我尝试 运行 再次申请更新其他资源,我会收到一条错误消息,指出 NSG 资源已经存在。

Error: A resource with the ID
"/subscriptions/0000000000000000/resourceGroups/SynthArtInfra/providers/Microsoft.Network/networkSecurityGroups/SynthArtInfra_ServerPoolNSG"
already exists - to be managed via Terraform this resource needs to be
imported into the State. Please see the resource documentation for
"azurerm_network_security_group" for more information.

为什么 Terraform 抱怨现有资源本应在其控制之下?

编辑: 这是与 NSG 相关的代码,其他一切都与 VPN 网关有关:

# Configure the Azure provider
terraform {
  required_providers {
    azurerm = {
      source = "hashicorp/azurerm"
      version = ">= 2.26"
    }
  }
}

provider "azurerm" {
  features {}
}

data "azurerm_resource_group" "SynthArtInfra" {
    name     = "SynthArtInfra"
    location = "Somewhere" # not real
    most_recent = true
}


resource "azurerm_virtual_network" "SynthArtInfra_ComputePool" {
  name = "SynthArtInfra_ComputePool"
  location = azurerm_resource_group.SynthArtInfra.location
  resource_group_name = azurerm_resource_group.SynthArtInfra.name
  address_space = ["10.6.0.0/16"]
}

resource "azurerm_subnet" "ComputePool_default" {
  name = "ComputePool_default"
  resource_group_name = azurerm_resource_group.SynthArtInfra.name
  virtual_network_name = azurerm_virtual_network.SynthArtInfra_ComputePool.name
  address_prefixes = ["10.6.0.0/24"]
}


resource "azurerm_network_security_group" "SynthArtInfra_ComputePoolNSG" {
  name                = "SynthArtInfra_ComputePoolNSG"
  location            = azurerm_resource_group.SynthArtInfra.location
  resource_group_name = azurerm_resource_group.SynthArtInfra.name

  security_rule {
    name                       = "CustomSSH"
    priority                   = 119
    direction                  = "Inbound"
    access                     = "Allow"
    protocol                   = "*"
    source_port_range          = "*"
    destination_port_range     = "0000" # not the real port number
    source_address_prefix      = "*"
    destination_address_prefix = "*"
  }    
   
}

另一件奇怪的事情是我们的订阅有一个安全策略,可以自动将 NSG 添加到没有 NSG 的资源中。但奇怪的是,在应用我的 terraform 脚本后,NSG 已创建但实际上并未与子网相关联,并且安全策略已创建新的 NSG。这需要解决,但没想到会导致这个错误。

我认为这是我第一次使用 Terraform,所以我在应用和销毁操作的中途遇到了很多错误。

我最终手动删除了 Azure 中的所有资源并删除了 Terraform 的本地缓存,然后一切都开始工作了。