如何自动将资源导入 Terraform 状态?
How to automatically import resource to Terraform state?
我想开发一个单一的 Terraform 模块来部署我的资源,并将资源存储在单独的 YAML 文件中。例如:
# resource_group_a.yml
name: "ResourceGroupA"
location: "westus"
# resource_group_b.yml
name: "ResourceGroupB"
location: "norwayeast"
以及以下 Terraform 模块:
# deploy/main.tf
variable source_file {
type = string # Path to a YAML file
}
locals {
rg = yamldecode(file(var.source_file))
}
resource "azurerm_resource_group" "rg" {
name = local.rg.name
location = local.rg.location
}
我可以部署资源组:
terraform apply -var="source_file=resource_group_a.yml"
terraform apply -var="source_file=resource_group_b.yml"
但后来我 运行 遇到了 2 个问题,因为 Terraform 保留了我的基础设施的状态:
- 如果我部署资源组 A,它会删除资源组 B,反之亦然。
- 如果我在 运行 宁
apply
之前手动删除 .tfstate
文件,并且资源组已经存在,我会得到一个错误:
A resource with the ID "/..." already exists - to be managed via Terraform
this resource needs to be imported into the State.
with azurerm_resource_group.rg,
on main.tf line 8 in resource "azurerm_resource_group" "rg"
我可以使用
将资源导入我的状态
terraform import azurerm_resource_group.reg "/..."
但是文件很长,可能需要导入多个资源。
所以我的问题是:
- 如何保持两个资源组之间的状态分离?
- 如何在我运行
terraform apply
时自动导入现有资源?
How to keep the state separate between the two resource groups?
我建议为此使用 Terraform Workspaces,这将为您提供单独的状态文件,每个文件都有一个关联的工作区名称。
How to automatically import existing resources when I run terraform
apply?
这目前是不可能的。有一些第三方工具,例如 Terraformer 用于完成自动导入,但根据我的经验,它们工作得不是很好,或者它们从不支持您需要的所有资源类型。即便如此,他们也不会在您每次 运行 terraform apply
.
时自动导入资源
我想开发一个单一的 Terraform 模块来部署我的资源,并将资源存储在单独的 YAML 文件中。例如:
# resource_group_a.yml
name: "ResourceGroupA"
location: "westus"
# resource_group_b.yml
name: "ResourceGroupB"
location: "norwayeast"
以及以下 Terraform 模块:
# deploy/main.tf
variable source_file {
type = string # Path to a YAML file
}
locals {
rg = yamldecode(file(var.source_file))
}
resource "azurerm_resource_group" "rg" {
name = local.rg.name
location = local.rg.location
}
我可以部署资源组:
terraform apply -var="source_file=resource_group_a.yml"
terraform apply -var="source_file=resource_group_b.yml"
但后来我 运行 遇到了 2 个问题,因为 Terraform 保留了我的基础设施的状态:
- 如果我部署资源组 A,它会删除资源组 B,反之亦然。
- 如果我在 运行 宁
apply
之前手动删除.tfstate
文件,并且资源组已经存在,我会得到一个错误:
A resource with the ID "/..." already exists - to be managed via Terraform
this resource needs to be imported into the State.
with azurerm_resource_group.rg,
on main.tf line 8 in resource "azurerm_resource_group" "rg"
我可以使用
将资源导入我的状态terraform import azurerm_resource_group.reg "/..."
但是文件很长,可能需要导入多个资源。
所以我的问题是:
- 如何保持两个资源组之间的状态分离?
- 如何在我运行
terraform apply
时自动导入现有资源?
How to keep the state separate between the two resource groups?
我建议为此使用 Terraform Workspaces,这将为您提供单独的状态文件,每个文件都有一个关联的工作区名称。
How to automatically import existing resources when I run terraform apply?
这目前是不可能的。有一些第三方工具,例如 Terraformer 用于完成自动导入,但根据我的经验,它们工作得不是很好,或者它们从不支持您需要的所有资源类型。即便如此,他们也不会在您每次 运行 terraform apply
.