user2062360
user2062360

Reputation: 1523

using count.index in terraform?

I am trying to generate a bunch of files from templates. I need to replace the hardcoded 1 with the count.index, not sure what format terraform will allow me to use.

resource "local_file" "foo" {
  count = "${length(var.files)}"
  
  content  = "${data.template_file.tenant_repo_multi.1.rendered}"
  #TODO: Replace 1 with count index.
  filename = "${element(var.files, count.index)}"
}


data "template_file" "tenant_repo_multi" {

  count = "${length(var.files)}"
  template = "${file("templates/${element(var.files, count.index)}")}"

}

variable "files" {
  type    = "list"
  default = ["filebeat-config_filebeat.yml",...]
}

I am running with:

Terraform v0.11.7
+ provider.gitlab v1.0.0
+ provider.local v1.1.0
+ provider.template v1.0.0

Upvotes: 14

Views: 31949

Answers (1)

Nathan Smith
Nathan Smith

Reputation: 8347

You can iterate through the tenant_repo_multi data source like so -

resource "local_file" "foo" {
  count    = "${length(var.files)}"
  content  = "${element(data.template_file.tenant_repo_multi.*.rendered, count.index)}"
  filename = "${element(var.files, count.index)}"
}

However, have you considered using the template_dir resource in the Terraform Template provider. An example below -

resource "template_dir" "config" {
    source_dir      = "./unrendered"
    destination_dir = "./rendered"

    vars = {
        message = "world"
    }
}

Upvotes: 14

Related Questions