Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 510
user2062360 Avatar asked May 11 '18 23:05

user2062360


People also ask

What is the count in TerraForm?

The Terraform count is a meta-argument determined by the Terraform language. The count can utilize it with modules and with all resource types. Also, the count meta-argument supports a whole number moreover makes that many instances of the resource or module.

What is the use of Count meta-argument in TerraForm?

The count meta-argument generates numerous resources of a module. You use the count argument within the block and assign a whole number (could by variable or expression), and Terraform generates the number of resources. Each resource is its discrete object generated, refreshed, or destroyed when performing the “ terraform apply .”

How does terraform distinguish between a block and an instance?

When count is set, Terraform distinguishes between the block itself and the multiple resource or module instances associated with it. Instances are identified by an index number, starting with 0. <TYPE>.<NAME> or module.<NAME> (for example, aws_instance.server) refers to the resource block.

How do I create multiple instances of a resource in TerraForm?

Terraform has two ways to do this: count and for_each. If a resource or module block includes a count argument whose value is a whole number, Terraform will create that many instances.


1 Answers

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"
    }
}
like image 173
Nathan Smith Avatar answered Oct 17 '22 03:10

Nathan Smith