Templatefile Function

In this chapter, we will learn the templatefile function in detail.

templatefile#

Sometimes we want to use a file but do not know all of the values before we run the project. Other times, the values are dynamic and generated as a result of a created resource. To use dynamic values in a file, we need to use the templatefile function.

The templatefile function allows us to define placeholders in a template file and then pass their values at runtime.

Project example#

Let’s dive into a simple example to see how it works. Clicking the terminal will run terraform init and then terraform apply. When prompted, enter yes to run the project.

This code requires the following environment variables to execute:
access_key_id
Not Specified...
secret_access_key
Not Specified...
/
example.tpl
main.tf
Templatefile function example project

Code explanation#

Let’s walk through the code we have written so we can understand what is going on:

  • We define a local (as we learned in the locals chapter) called rendered.

  • We set the value of the local (remember a local can have a value that is an expression) to the result of calling the templatefile function.

  • The template file function takes two arguments.

    • The first argument is the path to the template file.

    • In this example, we are using the relative path between the main.tf and the template file example.tpl, so the path is ./example.tpl.

    • The next parameter is a set of variables that we want to replace in our template.

    • We pass in a value for a name (kevin) and number (7).

      You could set the value of these variables to any expression such as another local or an attribute from a created resource or a data source.

  • If you look at the example template code, you will see that we use the syntax ${<variable_name>} when we want to reference a passed-in variable.

    Terraform will replace ${name} in our template with the value passed in for the name, it will do the same with ${number}.

We then use an output to print the rendered value of the template out to the terminal. This is an easy way for us to see how the templatefile function works.

Project output#

Let’s see templates in action. You will see the following output rendered:

Project example output

You can see that Terraform replaced the placeholders in our template with the values that we provided to the templatefile function. Thus, we see the message with kevin and 7 in it rather than the placeholders.

📝Note: Once you are done with the project, do not forget to run terraform destroy and then confirm with yes to delete all of the resources in this project.

Files
Loops in a Template
Mark as Completed
Report an Issue