'How to use a variable in place of file in templatefile function?

Is it possible to use a string variable in place of the filename in the templatefile function call?

https://www.terraform.io/language/functions/templatefile

templatefile(path, vars)



Solution 1:[1]

Yes, a path can be a variable:

templatefile(var.mytemplate, vars)

Solution 2:[2]

Here is something I have used and it worked:

main.tf

variable "templatefile" {
    default = "filter.tftpl"
  
}

resource "local_file" "one" {
    content  = templatefile("${path.module}/${var.templatefile}", { response_code = local.file_one_response_code })
    filename = "${path.module}/one"
}

resource "local_file" "two" {
    content  = templatefile("${path.module}/${var.templatefile}", { response_code = local.file_two_response_code })
    filename = "${path.module}/two"
}

filter.tftpl

metric.type="loadbalancing.googleapis.com/https/request_count" AND
metric.label.response_code_class="${response_code}" AND
resource.type="https_lb_rule" AND
resource.label.url_map_name = "myurlname"

locals.tf

locals {
  file_one_response_code = "400"
  file_two_response_code = "500"
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Marcin
Solution 2 Victor Biga