我想开发一个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"
但后来我遇到了两个问题,这是由于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
时自动导入现有资源
如何保持两个资源组之间的状态分离?
我建议使用Terraform Workspaces,它将为您提供单独的状态文件,每个文件都有一个相关的工作区名称。
如何在运行terraform时自动导入现有资源申请
这目前是不可能的。有一些第三方工具,比如Terraformer,可以实现自动导入,但根据我的经验,它们工作得不太好,或者它们永远不支持你需要的所有资源类型。即便如此,它们也不会在每次运行terraform apply
时自动导入资源。