简体   繁体   中英

How to create multiple resources with different names and target files with Terraform?

For example, there are many JSON files in the path

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

I want to create multiple tasks with different ids

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
}

...

Put them into one resource, is there a way to use for_each?

You can do this with for_each . For example:

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
}

Once this is done, you can refer to individual instances of aws_dms_replication_task using key value. For example:

aws_dms_replication_task.test["task1"].replication_task_arn

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM