The Template resource allows the processing of templates, outputing the result as a file.
Templating uses the Handlebars language.
Examples
Template using HereDoc
The following example shows how the template can be embedded into the resource stanza using HereDoc syntax.
Copy resource "template" "consul_config" {
source = <<-EOF
data_dir = "{{data_dir}}"
log_level = "DEBUG"
datacenter = "dc1"
primary_datacenter = "dc1"
server = true
bootstrap_expect = 1
ui = true
bind_addr = "0.0.0.0"
client_addr = "0.0.0.0"
advertise_addr = "10.6.0.200"
ports {
grpc = 8502
}
connect {
enabled = true
}
EOF
destination = "./consul_config/consul.hcl"
variables = {
data_dir = "/tmp"
}
}
The file produced from this example would look like the following
Copy data_dir = "/tmp"
log_level = "DEBUG"
datacenter = "dc1"
primary_datacenter = "dc1"
server = true
bootstrap_expect = 1
ui = true
bind_addr = "0.0.0.0"
client_addr = "0.0.0.0"
advertise_addr = "10.6.0.200"
ports {
grpc = 8502
}
connect {
enabled = true
}
External Files
To leverage external files you can use the file function which loads a file returning a string. This example also shows how interpolation can be used to ensure a template is processed before it is consumed.
Copy resource "template " consul_config " {
source = file(" . / mytemplate.hcl ")
destination = " . / consul_config / consul.hcl "
variables = {
data_dir = " / tmp "
}
}
container " consul " {
depends_on = [" template.consul_config "]
image {
name = " consul : ${variable.consul_version} "
}
command = [" consul ", " agent ", " - config-file =/ config / consul.hcl "]
volume {
source = resource.template.consul_config.destination
destination = " / config / consul.hcl "
}
}
Inline variables
Copy resource "template" "consul_config" {
source = <<-EOF
data_dir = " ${ data( "test" ) } "
log_level = "DEBUG"
datacenter = " ${ variable . datacenter } "
server = ${ variable . server }
EOF
destination = "./consul_config/consul.hcl"
}
Template helpers
The template
resource provides helpers that can be used inside your templates as shown in the example below.
Copy resource "template" "consul_config" {
source = <<-EOF
file_content = "{{ file "./myfile.txt" }}"
quote = {{quote something}}
trim = {{quote (trim with_whitespace)}}
EOF
destination = "./consul_config/consul.hcl"
}
quote
Returns the original string wrapped in quotations, quote can be used with the Go template pipe modifier.
Copy // given the string 'abc'
quote "abc" // would return the value '"abc"'
trim
Removes whitespace such as carrige returns and spaces from the begining and the end of the string, can be used with the Go template pipe modifier.
Copy // given the string ' abc '
trim " abc " // would return the value 'abc'