Skip to main content

Using Filesystem Functions

1. Using file Function

Function Signature Description Example
file file(path) Returns the contents of a file at the given path as a string.
data "external" "file_content" {
  program = ["sh", "-c", "cat ${var.file_path}"]
}

Example: Reading a File

resource "local_file" "example" {
  content = file("example.txt")
  filename = "output.txt"
}
Note: The file function reads the file at runtime during plan/apply, not at configuration time.

2. Using fileexists Function

Function Signature Description Examples
fileexists fileexists(path) Returns true if the file at the given path exists, false otherwise. fileexists("./config.json")

Example: Check if a file exists before reading it

data "local_file" "config" {
  count = fileexists("./config.json") ? 1 : 0
  filename = "./config.json"
}
Note: The fileexists function is useful for conditional logic in Terraform configurations, particularly when you want to handle files that may or may not be present.

3. Using fileset Function

The fileset function in Terraform allows you to read a set of files from the filesystem based on a pattern. It is particularly useful for managing configuration files or templates in a structured way.

Argument Description Example
path The directory path to search for files. ./templates
pattern A glob pattern to match files within the directory. *.tf

Example: Using fileset to read all .tf files in a directory

data "terraform_remote_state" "example" {
  backend = "local"
  config = {
    path = "./state.tf"
  }
}

locals {
  tf_files = fileset("./templates", "*.tf")
}
Note: The fileset function returns a list of file paths relative to the working directory. It does not read or parse the contents of the files.

4. Using filebase64 Function

Function Signature Description Example
filebase64 filebase64(path) Returns the base64-encoded content of a file at the given path
data "template_file" "example" {
  filename = "${path.module}/example.txt"
}

output "file_content_base64" {
  value = data.template_file.example.content
}

Example: Reading a file and encoding it in base64

data "local_file" "my_file" {
  filename = "./config.json"
}

output "base64_content" {
  value = data.local_file.my_file.content_base64
}

5. Using templatefile Function

Argument Description Example
templatefile() Reads a template file and renders it with the given variables templatefile("template.tmpl", { name = "John" })

Example: Basic usage of templatefile

resource "aws_instance" "web" {
  ami           = data.aws_ami.ubuntu.id
  instance_type = "t3.micro"
  user_data     = templatefile("user-data.sh", {
    server_port = 8080
    ssl_enabled = true
  })
}

Example: Template file (user-data.sh)

#!/bin/bash
if [ "${ssl_enabled}" = "true" ]; then
  echo "SSL is enabled"
else
  echo "SSL is disabled"
fi

echo "Server port: ${server_port}"

6. Using abspath Function

Function Signature Description Examples
abspath abspath(path) Returns the absolute path of a given path string. abspath("./config") // /home/user/project/config

Example: Resolving Relative Paths

resource "local_file" "config" {
  content = "Config file content"
  filename = abspath("./config.tf")
}

7. Using dirname and basename Functions

Function Description Example Notes
dirname Returns the directory portion of a file path dirname("/home/user/file.txt") Removes the filename and trailing slash from a path
basename Returns the filename portion of a file path basename("/home/user/file.txt") Extracts the final component of a path

Example: Using dirname and basename

const filePath = "/var/log/application.log";

// Extract directory path
const dirPath = dirname(filePath);
// Result: "/var/log"

// Extract filename
const fileName = basename(filePath);
// Result: "application.log"
Note: These functions are particularly useful in Terraform when working with file paths for modules or data sources that require path manipulation.

8. Using pathexpand Function

Function Signature Description Example
pathexpand pathexpand(path) Expands a path by replacing ~ with the user's home directory and environment variables like $HOME or ${HOME}. pathexpand("~/myproject")

Example: Expanding a Path with Tilde

output "expanded_path" {
  value = pathexpand("~/myproject/config.tf")
}

Example: Using Environment Variables

output "expanded_with_env" {
  value = pathexpand("${HOME}/myproject/config.tf")
}

9. Using filemd5 and filesha256 Functions

Function Description Example
filemd5() Calculates the MD5 hash of a file's contents
resource "aws_s3_object" "example" {
  bucket = "my-bucket"
  key    = "example.txt"
  source = "./example.txt"
  etag   = filemd5("./example.txt")
}
filesha256() Calculates the SHA256 hash of a file's contents
resource "aws_s3_object" "example" {
  bucket = "my-bucket"
  key    = "example.txt"
  source = "./example.txt"
  etag   = filesha256("./example.txt")
}
Note: These functions are useful for tracking file changes in state files, particularly when used with etag attributes to ensure S3 objects are updated only when their content changes.

10. Using templatestring Function

Function Signature Description Example
templatestring templatestring(format, args...) Formats a string using Go's fmt.Sprintf-style formatting. templatestring("Hello %s, you are %d years old", "Alice", 30)

Example: Basic Usage

output "greeting" {
  value = templatestring("Hello %s, welcome to %s!", "John", "Terraform")
}

Example: With Numbers

output "formatted_number" {
  value = templatestring("The count is %d and the price is $%.2f", 5, 19.99)
}

Was this article helpful?