如何在模板文件函数中使用变量代替文件?

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

是否可以在模板文件函数调用中使用字符串变量代替文件名?

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

模板文件(路径,变量)

是的,一个path可以是一个变量:

templatefile(var.mytemplate, vars)

这是我用过并且有效的东西:

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