lev
lev

Reputation: 4127

include a terraform template in another template

I have many template files that are used by terraform scripts, all template files have some common part, ie:

file a.tmpl:

env=prod
var=a
-------------------
file b.tmpl:

env=prod
var=b

I would like to export the common part to a separate file, so that it won't have to repeat in every file, something like:

file base.tmpl:
env=prod
-------------------
file a.tmpl:

%{ include "base.tmpl" }
var=a
-------------------
file b.tmpl:

%{ include "base.tmpl" }
var=b

but that feature doesn't exists

(it is very similar to django templates feature as described here: https://stackoverflow.com/a/10985987/245024)

is there a way to do the include somehow?


I was able to do a workaround by concating the files like this:

data "template_file" "vars_a" {
  template = "${format("%s \n %s", 
    file("${path.module}/base.tmpl"), 
    file("${path.module}/a.tmpl")
   )}"
}

but that is more limiting then including the base template directly in the file.

Upvotes: 3

Views: 3784

Answers (1)

Marcin
Marcin

Reputation: 238199

I think you could use templatefile:

a.tmpl

${file("base.tmpl")}
var=a

base.tmpl

var_ddd=ffff
var_sss=adfs

main.tf

data "template_file" "vars_a" {
  template = templatefile("a.tmpl", {})
}

output "test" {
  value = data.template_file.vars_a.template
}

Upvotes: 4

Related Questions