简体   繁体   中英

How to iterate resources in terraform?

How to iterate resources for different values of a parameter

For example, in my below terraform file I have one data block and one resource. If I pass value DB_NAME=test then its working fine. But what if I have multiple values of DB_NAME and I want it to run multiple time DB_NAME=test, app . How will I iterate over data and resource block? :

data "template_file" "search-index" {
  template = "${file("search-index/search-index.sh")}"

  vars {
    DB_NAME = "${var.DB_NAME}"

  }
}

resource "null_resource" "script" {

  triggers = {
    DB_NAME = "${var.DB_NAME}"
    script_sha = "${sha256(file("search-index/search-index.sh"))}"
  }

  provisioner "local-exec" {
    command   = "${data.template_file.search-index.rendered}"
    interpreter = ["/bin/bash", "-c"]
  }
}

I'm not sure if I fully understood what you are trying to achieve but you can create multiple DB by defining a variables.tf like this:

variable "DB_NAME" {
  description = "A list of databases"
  type        = list(string)
  default     = ["db1", "db2", "db3"]
}

And then using the for_each functionality in your terraform file:

data "template_file" "search-index" {
  for_each = toset(var.DB_NAME)
  template = "${file("search-index/search-index.sh")}"

  vars = {
    DB_NAME = each.value
  }
}
resource "null_resource" "script" {
  for_each = toset(var.DB_NAME)
  triggers = {
    DB_NAME = each.value
    script_sha = "${sha256(file("search-index/search-index.sh"))}"
  }

  provisioner "local-exec" {
    command   = "${data.template_file.search-index[each.value]}"
    interpreter = ["/bin/bash", "-c"]
  }
}

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