terraform - 获取 Terraform 资源已存在错误与 Terraform 刚刚创建的资源
问题描述
我正在使用 Terraform 在 Azure 中建立一个虚拟网络。
我有几个 VNet,每个 VNet 都有自己的网络安全组 100% 在 Terraform 中管理,在运行 Terraform 之前除了资源组之外不存在任何资源。
当我Terraform apply
第一次运行时,所有资源都正确创建。但是,如果我尝试再次运行 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 添加到没有的资源中。但奇怪的是,在应用我的 terraform 脚本后,创建了 NSG,但实际上并未与子网关联,并且安全策略创建了新的 NSG。这需要解决,但不认为会导致此错误。
解决方案
我认为这是我第一次使用 Terraform,所以我在应用和销毁操作的中途遇到了很多错误。
我最终手动删除了 Azure 中的所有资源并删除了 Terraform 的本地缓存,然后一切都开始工作了。
推荐阅读
- python - Django 表单日期时间字段
- docker - Kubernetes docker 容器中的前端 Vue.js 应用程序无法连接到后端
- javascript - 将 VueJS 前端连接到 Golang 后端
- android - 使用唯一标识符flutter / android识别设备
- json - Scala 将 Map[String, Long] 转换为 JSON 或 JSON 字符串
- javascript - React 无需导入即可工作
- javascript - d3.js:在多个图表上同步画笔选择
- python - 在具有多个数字列的数据框中显示每个组的前 5 行
- azure - Azure WCF 服务可通过 WcfTestClient 访问,但不能通过浏览器或 MVC 站点访问
- vue.js - 在 Vue 中观察/观察 DOM 子节点的数量