Terraform for 循环创建多重资源

Terraform for loop with creating of multiply resources

我在aws
中有简单的glue job 这是一个例子:

resource "aws_glue_job" "myjob1" {
  name     = "myjob1"
  role_arn = var.role_arn

  command {
    name = "pythonshell"
    python_version = 3
    script_location = "s3://mybucket/myjob1/run.py"
  }
}

它正在工作,但如果我有类似列表 myjob1,myjob2,myjob3,myjob4,myjob5 的东西。
可能是,来自 bash:

的这个深奥的例子
listjobs="myjob1 myjob2 myjob3 myjob4 myjob5"

for i in ${listjobs}; do
resource "aws_glue_job" "$i" {
  name     = "$i"
  role_arn = var.role_arn

  command {
    name = "pythonshell"
    python_version = 3
    script_location = "s3://mybucket/$i/run.py"
  }
}
done

在 terraform 中是真实的?

如果您的 listjobs 是:

variable "listjobs" {
  default = ["myjob1", "myjob2", "myjob3", "myjob4", "myjob5"]
}

然后您可以在 terraform 中使用 count 来创建多个 aws_glue_job:

resource "aws_glue_job" {

  count = length(var.listjobs)  

  name     = var.listjobs[count.index]

  role_arn = var.role_arn

  command {
    name = "pythonshell"
    python_version = 3
    script_location = "s3://mybucket/${var.listjobs[count.index]}/run.py"
  }

}

我通过 for loop 解决了这个问题。 在variables.tf

variable "list_of_jobs" {
  default = ["myjob1","myjob2","myjob3"]
}

glue.tf

resource "aws_glue_job" "this" {
  for_each = toset(var.list_of_jobs)
  name     = each.value
  role_arn = var.role_arn

  command {
    name = "pythonshell"
    python_version = 3
    script_location = "s3://mybucket/${each.value}/run.py"
  }
}