Terraform – FotD – file()

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.

What is it?

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)}"
}

Example 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"

Why use it?

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.

Lessons Learned

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.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.