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

如何使用Terraform for_each批量创建不同名称及配置文件的资源

方案说明

完全可以通过for_each结合文件扫描函数实现批量创建,无需逐个编写重复的资源块,具体实现如下:

1. 实现逻辑

通过fileset函数扫描当前模块下符合命名规则的JSON配置文件,提取文件名作为for_each的唯一索引,批量生成资源实例。

2. 完整代码示例

# 预处理配置文件,生成供for_each遍历的映射表
locals {
  # 扫描当前模块目录下所有test开头的json文件,生成 {文件名前缀: 完整文件名} 的映射
  dms_task_configs = {
    for config_file in fileset(path.module, "test*.json") :
    trimsuffix(config_file, ".json") => config_file
  }
}

# 单资源块批量创建所有DMS复制任务
resource "aws_dms_replication_task" "batch_tasks" {
  for_each = local.dms_task_configs

  replication_task_id       = "test-dms-replication-task-tf-${each.key}"
  table_mappings            = file("${path.module}/${each.value}")
  source_endpoint_arn       = aws_dms_endpoint.test-dms-source-endpoint-tf.endpoint_arn
  target_endpoint_arn       = aws_dms_endpoint.test-dms-target-endpoint-tf.endpoint_arn
  # 其余公共配置参数可统一在此处添加
}

3. 说明事项

  • 新增/删除配置文件时无需修改资源代码,Terraform会自动识别变更,调整对应资源实例
  • 资源实例的唯一标识由文件名前缀决定,避免了列表索引变动导致的资源误删问题
  • 如需引用某一个具体的任务实例,可通过aws_dms_replication_task.batch_tasks["test1"]的格式调用
  • 若需要适配其他命名规则的配置文件,只需修改fileset函数中的匹配规则即可,例如扫描所有JSON文件可修改为fileset(path.module, "*.json")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 23:39:04