This is part of an ongoing series of posts documenting the built-in interpolation functions in Terraform. For more information, check out the beginning post. In this post I am going to cover the file() function. The example file is on GitHub here.
Function name: file(path)
Returns: Takes a path to a file and reads the content of the file into a string variable. Returns the string value.
Example:
variable "file" {
default = "/path/to/file.txt"
}
# Returns string of file contents
output "file_output" {
value = "${file(var.file)}"
}
##############################################
# Function: file
##############################################
##############################################
# Variables
##############################################
variable "file1" {}
variable "file2" {}
##############################################
# Resources
##############################################
##############################################
# Outputs
##############################################
output "file_output" {
value = "${file(var.file1)}"
}
output "path_file_output" {
value = "${file("${path.cwd}\\${var.file2}")}"
}
Run the following from the file folder to get example output for a number of different cases:
terraform apply -var 'file1=input.txt' -var "file2=input.txt"
terraform apply -var 'file1=.\\input.txt' -var "file2=input.txt"
terraform apply -var 'file1=.\\module\\mod_input.txt' -var "file2=input.txt"
terraform apply -var "file1=.\\module\\input-noext" -var "file2=input.txt"
I’ve definitely had to pull file contents into Terraform to use with other resources. Sometimes you have to copy a file to a destination. Other times the file contains a template that you will use with the template resource. You might also pull in a CSV or something similar to work as a data source.
The function will read in the file as a single string and will not perform any interpolation. If you want to do something like that, you will need to use the template resource to leverage those functions. You can also use the path.PATH built-in variable to reference the path in the Terraform configuration. The way to call it is a little weird, so I included an example in the output values. The function doesn’t care if the file has an extension on it. You cannot give it a directory, as it will throw an error.
Coming up next is the floor() function.
October 18, 2024
What's New in the AzureRM Provider Version 4?
August 27, 2024
Debugging the AzureRM Provider with VSCode
August 20, 2024
State Encryption with OpenTofu
August 1, 2024