You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Terraform使用moved{}将count转for_each时遇不支持错误求助

解决Terraform中moved块报错"Unsupported block type"的问题

错误原因

moved块不能嵌套在resource、module等块内部,必须作为根模块的直接子块(或子模块的根层级),与resource块同级。

正确操作步骤

1. 调整moved块的位置

将moved块从resource内部移出,放在.tf文件的根层级,和resource块并列。

2. 编写正确的moved映射规则

根据从count转for_each的需求,分两种场景处理:

场景1:Terraform版本 < 1.5(手动逐个映射)

若你的Terraform版本低于1.5,不支持在moved块中使用for循环,需手动为每个实例编写映射规则:

# 根层级的moved块,与resource同级
moved {
  from = azurerm_app_service_plan.example[0]
  to   = azurerm_app_service_plan.example["0"]
}

moved {
  from = azurerm_app_service_plan.example[1]
  to   = azurerm_app_service_plan.example["1"]
}

# 原resource块修改为for_each模式
resource "azurerm_app_service_plan" "example" {
  for_each = tomap({ for i in range(var.instance_count) : tostring(i) => i })
  
  # 将原count.index替换为each.key或each.value
  name = "asp-${each.key}"
  # 其他原有配置项...
}

场景2:Terraform版本 >= 1.5(用for循环批量映射)

若版本满足1.5及以上,可通过for循环批量生成moved规则,提升效率:

# 根层级的moved块,批量映射count索引到for_each的字符串键
moved {
  for i in range(var.instance_count)
  from = azurerm_app_service_plan.example[i]
  to   = azurerm_app_service_plan.example[tostring(i)]
}

# 原resource块修改为for_each模式
resource "azurerm_app_service_plan" "example" {
  for_each = tomap({ for i in range(var.instance_count) : tostring(i) => i })
  
  name = "asp-${each.key}"
  # 其他原有配置项...
}

3. 验证并执行

  • 运行terraform plan,检查输出是否显示Move "..." to "..."的迁移计划,而非资源销毁重建
  • 确认计划符合预期后,执行terraform apply完成状态迁移

内容的提问来源于stack exchange,提问作者user25544072

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.22 13:46:01