如何用Terraform创建多个不同名称的资源和目标文件?多个、如何用、不同、名称

2023-09-04 02:22:21 作者:辜負.

例如,路径中有许多JSON文件

./test1.json
./test2.json
./test3.json
...

我想用不同的ID创建多个任务

resource "aws_dms_replication_task" "test1" {
  replication_task_id       = "test-dms-replication-task-tf-test1"
  table_mappings            = file("${path.module}/test1.json")
  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
}

resource "aws_dms_replication_task" "test2" {
  replication_task_id       = "test-dms-replication-task-tf-test2"
  table_mappings            = file("${path.module}/test2.json")
  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
}

...
云脉文档识别 电子图像美化功能提升识别准确率

将它们放到一个资源中,有没有办法使用for_each?

推荐答案

您可以使用for_each执行此操作。例如:

variable "rule_files" {
   default = ["test1", "test2", "test3"]
}


resource "aws_dms_replication_task" "test" {

  for_each                  = var.rule_files

  replication_task_id       = "test-dms-replication-task-tf-${each.key}"
  table_mappings            = file("${path.module}/${each.key}.json")
  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
}

完成后,您可以使用key value引用aws_dms_replication_task的单个实例。例如:

aws_dms_replication_task.test["task1"].replication_task_arn