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



我正在使用Terraform在Azure中建立一个虚拟网络。

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

当我第一次正确创建所有资源时,运行Terraform apply。但是,如果我再次尝试运行application来更新其他资源,我会收到一个错误,说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的资源中。但奇怪的是,在应用了我的地形脚本后,创建了NSG,但实际上并没有与子网相关联,而且安全策略创建了新的NSG。这需要解决,但我认为这不会导致此错误。

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

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

TLDR尝试删除您自己添加的资源之间的任何自定义依赖关系。

嗨,我在遇到类似问题时看到了这篇帖子,我会把我的解决方案放在这里,以防对其他人有帮助。

我正在通过Terraform创建一个云运行服务。第一次做得很好,它创建了我想要的资源,但一旦我再次运行应用程序,我就会收到这个错误,说已经存在一个同名的资源。这很奇怪,因为根据计划,它应该删除然后替换该资源。

发生的事情是,我在其他一些资源上添加了一个未成功的depends_on字段,这阻止了在尝试创建新资源之前删除云运行服务资源。

根据文档,只有当存在无法通过查看字段推断出的奇怪依赖关系时,才需要depends_on字段。所以我刚刚删除了依赖项之间的所有自定义关系,现在可以随心所欲地重新应用了。

相关内容

最新更新