sebastian
sebastian

Reputation: 2348

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)

Upvotes: 1

Views: 6616

Answers (2)

Victor Biga
Victor Biga

Reputation: 519

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

Upvotes: 1

Marcin
Marcin

Reputation: 238199

Yes, a path can be a variable:

templatefile(var.mytemplate, vars)

Upvotes: 3

Related Questions