Search code examples
amazon-web-servicesfor-loopforeachterraformaws-glue

Terraform for loop with creating of multiply resources


I have simple glue job in aws
This is an example:

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"
  }
}

It is working, but if I have something like list myjob1,myjob2,myjob3,myjob4,myjob5.
Could be, this esoteric example from 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

be real in terraform ?


Solution

  • I resolved this via for loop. In variables.tf

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

    In 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"
      }
    }