terraform 坚持认为资源已经存在,但当我尝试导入它时却说不存在

问题描述 投票:0回答:1

当我尝试使用 terraform 创建 azure 资源时,我不断遇到同样的问题:terraform 坚持认为某些资源已经存在。 它告诉我导入它们。 如果我这样做,它告诉我我需要先定义它们,因为我猜我从来没有设法获得正确的名称。 例如,我使用模块创建资源组。我将名称传递给模块,然后使用名称“this”在模块中创建它。 我不知道使用什么名称来解决导入问题。

module "example-resource-group" {
  source   = "./modules/resource-group"

  name     = "rg-example-${var.environment}"
  location = var.location
  tags     = local.tags
}

然后在

./modules/resource-group/main.tf

resource "azurerm_resource_group" "this" {
  location = var.location
  name     = var.name
  tags     = var.tags
}

这个最终的名字是什么?我怎样才能导入这个?

如果我从一片绿地开始,为什么它总是说资源存在?

azure terraform terraform-provider-azure
1个回答
0
投票

这个最终的名字是什么?我怎样才能导入这个?为什么总是说资源存在?

当您尝试创建已存在于 Azure 环境中的资源时,即使该资源不是由您或 terraform 创建的,也会显示如下格式的警告消息。

enter image description here

在这种场景下,terraform import您可以将资源导入到当前terraform状态配置中,以便在需要时处理资源。

也就是说,资源和模块都可以使用 terraform import 命令导入,只需稍加改动即可。

在您的情况下,当您导入模块时,您需要遵循

module.modulename.resourceprovidertype.resource
这种格式。

module.example-resource-group.azurerm_resource_group.this

注意:这里的

"this"
指的是模块配置
.tf
文件下的资源组资源。

更详细的相关信息请参阅博客

我尝试导入 terraform 环境中已存在的资源组,并成功导入,如下所示。

语法

terraform import module.example-resource-group.azurerm_resource_group.example <resource ID>

注意:模块内资源的名称是

"example"
,所以当我调用模块时,它指的是上述给定模块格式的资源。

terraform import module.example-resource-group.azurerm_resource_group.example /subscriptions/subscriptionID/resourceGroups/Jahnavi

enter image description here

导入后,验证它是否存在于

terraform.tfstate
文件配置中:

enter image description here

此外,您还可以使用

terraform state list
命令来验证导入资源的 terraform 状态配置。

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.