Bird
Raised Fist0
Terraformcloud~5 mins

File functions (file, templatefile) in Terraform - Commands & Configuration

Choose your learning style10 modes available
Introduction
Sometimes you need to use the contents of a file inside your Terraform configuration. The file and templatefile functions help you read files and use their content or templates to create dynamic configurations.
When you want to include a static configuration file content inside your Terraform resource.
When you need to generate a configuration file from a template with variables filled in.
When you want to keep your Terraform code clean by separating large text blocks into files.
When you want to reuse the same template with different values for multiple resources.
When you want to manage scripts or config files that your infrastructure needs.
Config File - main.tf
main.tf
variable "app_name" {
  type    = string
  default = "my-app"
}

variable "port" {
  type    = number
  default = 8080
}

resource "local_file" "static_config" {
  filename = "static_config.txt"
  content  = file("static_config.txt")
}

resource "local_file" "templated_config" {
  filename = "templated_config.txt"
  content  = templatefile("config_template.txt", { app_name = var.app_name, port = var.port })
}

This Terraform file defines two variables: app_name and port.

It creates two local files using the local_file resource:

  • static_config: reads the entire content of static_config.txt using the file function and writes it to a file.
  • templated_config: uses the templatefile function to read config_template.txt, replace variables app_name and port with values, and writes the result to a file.

This shows how to use both file functions to manage file contents and templates in Terraform.

Commands
Initialize the Terraform working directory to download required providers and set up the environment.
Terminal
terraform init
Expected OutputExpected
Initializing the backend... Initializing provider plugins... - Finding latest version of hashicorp/local... - Installing hashicorp/local v2.3.0... - Installed hashicorp/local v2.3.0 (signed by HashiCorp) Terraform has been successfully initialized! You may now begin working with Terraform. Try running "terraform plan" to see any changes that are required for your infrastructure.
Apply the Terraform configuration to create the local files with content from file and templatefile functions.
Terminal
terraform apply -auto-approve
Expected OutputExpected
local_file.static_config: Creating... local_file.static_config: Creation complete after 0s [id=static_config.txt] local_file.templated_config: Creating... local_file.templated_config: Creation complete after 0s [id=templated_config.txt] Apply complete! Resources: 2 added, 0 changed, 0 destroyed.
→
-auto-approve - Skip interactive approval to apply changes immediately
Show the content of the static file that was read and written by the file function.
Terminal
cat static_config.txt
Expected OutputExpected
This is a static configuration file. It contains fixed settings for the app.
Show the content of the templated file generated by the templatefile function with variables replaced.
Terminal
cat templated_config.txt
Expected OutputExpected
Application Name: my-app Listening Port: 8080
Key Concept

If you remember nothing else from this pattern, remember: use file() to read static file content and templatefile() to fill templates with variables inside Terraform.

Common Mistakes
Using file() when you need variable substitution inside the file content.
file() reads the file as-is without replacing variables, so your template variables remain unchanged.
Use templatefile() with a variables map to replace placeholders in the file content.
Providing incorrect file paths to file() or templatefile().
Terraform will fail to find the file and error out during plan or apply.
Ensure the file path is relative to the Terraform root directory or provide an absolute path.
Not defining variables used in templatefile() leading to errors.
Terraform cannot replace undefined variables and will fail.
Declare all variables used in the templatefile() call in your Terraform configuration.
Summary
Use the file() function to read the full content of a static file into Terraform.
Use the templatefile() function to read a file and replace variables with values.
Apply Terraform to create or update files with the desired content using these functions.

Practice

(1/5)
1. What does the Terraform function file() do?
easy
A. Writes content to a file
B. Reads a file and replaces variables inside it
C. Reads the entire content of a file as plain text
D. Deletes a file from the system

Solution

  1. Step 1: Understand the purpose of file()

    The file() function reads the content of a file and returns it as plain text without any processing.
  2. Step 2: Compare with other functions

    templatefile() replaces variables inside a file, but file() just reads raw content.
  3. Final Answer:

    Reads the entire content of a file as plain text -> Option C
  4. Quick Check:

    file() reads file content [OK]
Hint: file() just reads text, no variable replacement [OK]
Common Mistakes:
  • Confusing file() with templatefile()
  • Thinking file() modifies file content
  • Assuming file() writes to files
2. Which of the following is the correct syntax to use templatefile() in Terraform?
easy
A. templatefile("path/to/file.tpl", { var1 = "value1" })
B. templatefile(path = "file.tpl", vars = { var1 = "value1" })
C. templatefile("file.tpl", var1 = "value1")
D. templatefile("file.tpl")

Solution

  1. Step 1: Recall the correct function signature

    templatefile() requires two arguments: the file path as a string and a map of variables.
  2. Step 2: Match the syntax

    templatefile("path/to/file.tpl", { var1 = "value1" }) correctly passes the file path and a map with variable assignments. Other options either use wrong parameter names or omit the variables map.
  3. Final Answer:

    templatefile("path/to/file.tpl", { var1 = "value1" }) -> Option A
  4. Quick Check:

    templatefile(path, vars map) syntax [OK]
Hint: templatefile needs path string and vars map [OK]
Common Mistakes:
  • Using named parameters instead of positional
  • Passing variables outside a map
  • Omitting the variables map argument
3. Given the file message.tpl with content:
Hello, ${name}!

What is the output of this Terraform expression?
templatefile("message.tpl", { name = "Alice" })
medium
A. Hello, Alice!
B. Hello, ${name}!
C. templatefile("message.tpl", { name = "Alice" })
D. Error: variable 'name' not found

Solution

  1. Step 1: Understand templatefile variable replacement

    The templatefile() function reads the file and replaces variables like ${name} with the provided value.
  2. Step 2: Apply the variable substitution

    Since name is set to "Alice", the output becomes "Hello, Alice!".
  3. Final Answer:

    Hello, Alice! -> Option A
  4. Quick Check:

    templatefile replaces variables [OK]
Hint: templatefile replaces ${var} with values from map [OK]
Common Mistakes:
  • Expecting raw template text output
  • Confusing file() with templatefile() output
  • Missing variable in map causing error
4. You wrote this Terraform code:
output "config" {
  value = templatefile("config.tpl", { env = "prod" })
}

But Terraform shows an error: File not found: config.tpl. What is the likely cause?
medium
A. The file config.tpl is empty
B. The variable env is missing in the map
C. templatefile() cannot be used in output blocks
D. The file config.tpl does not exist in the working directory

Solution

  1. Step 1: Analyze the error message

    The error says "File not found", which means Terraform cannot locate the file config.tpl.
  2. Step 2: Check file existence and path

    Most likely, the file is missing or the path is incorrect. Variables missing or empty files do not cause this error.
  3. Final Answer:

    The file config.tpl does not exist in the working directory -> Option D
  4. Quick Check:

    File not found error means missing file [OK]
Hint: Check file path and existence if 'File not found' error [OK]
Common Mistakes:
  • Assuming variable map causes file not found
  • Thinking templatefile() is invalid in output
  • Ignoring file path correctness
5. You want to create a Terraform output that reads a JSON file data.json and replaces a placeholder ${region} inside it with your variable var.region. Which approach is best?
hard
A. Use file() to read data.json and then use replace() to substitute ${region}
B. Use templatefile() with data.json and pass { region = var.region } as variables
C. Use file() only, since it automatically replaces variables
D. Use templatefile() but pass an empty map for variables

Solution

  1. Step 1: Understand the difference between file() and templatefile()

    file() reads raw content without variable substitution. templatefile() reads and replaces variables inside the file.
  2. Step 2: Choose the correct function and usage

    Since you want to replace ${region} with var.region, templatefile() with a variables map is the best choice.
  3. Final Answer:

    Use templatefile() with data.json and pass { region = var.region } as variables -> Option B
  4. Quick Check:

    templatefile() replaces placeholders with variables [OK]
Hint: Use templatefile() to replace placeholders with variables [OK]
Common Mistakes:
  • Expecting file() to replace variables
  • Passing empty variable map to templatefile()
  • Using replace() manually instead of templatefile()
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard