DEV Community

Spacelift team for Spacelift

Posted on • Originally published at spacelift.io

How to Use Terraform File Function [Examples]

When setting up cloud infrastructure with Terraform, it's common to reference external files like scripts or configuration templates. Instead of cluttering your code with large inline content, you can keep things clean and modular by loading these files separately. 

In this article, we'll show how to load external files into your configuration using the Terraform file function.

What is the Terraform file function?

The file() function in Terraform reads the contents of a file from disk and returns it as a string. It reads files from the machine where Terraform is executed (your workstation or CI), not from remote servers.

It is typically used to load configuration files, certificates, scripts, or other external resources into Terraform configurations. 

Best practices when using the file() function:

  • Always verify the file path using terraform console or terraform plan if you're unsure.
  • For portability, combine it with path.module or path.root and consider pathexpand() if you need to support ~ paths.
  • Avoid using file() for binary files, as it's meant for reading text files only. Use filebase64() instead for binaries.
  • If you need to inject variables into a script or template, use templatefile() rather than file().

Example 1: Injecting a shell script into a cloud instance

In this example, the file() function is used to load the contents of a local startup.sh file and assign it to the user_data field of an EC2 instance. AWS EC2 allows user_data to be passed to configure the instance during boot time - typically for installing packages, running scripts, or setting up the environment.

resource "aws_instance" "example" {
  ami           = "ami-1234567890abcdef0"
  instance_type = "t2.micro"

  user_data = file("${path.module}/startup.sh")
}
Enter fullscreen mode Exit fullscreen mode

Using file() here allows Terraform to inject the contents of the script directly, which is more maintainable than hardcoding the script inline. You can also modify the script without touching the Terraform code, making this approach modular and clean.

Example 2: Loading an SSH public key

This example uses the file() function to read the contents of a local SSH public key (id_rsa.pub) and create an AWS key pair. The public_key argument requires the entire key content as a string, and using file() ensures the correct data is supplied in a clean and readable way.

resource "aws_key_pair" "deployer" {
  key_name   = "deployer-key"
  public_key = file("~/.ssh/id_rsa.pub")
}
Enter fullscreen mode Exit fullscreen mode

This is particularly useful when you're provisioning virtual machines and want to allow SSH access using your local public key. Instead of copying and pasting the key into the configuration, you can maintain it in a file, which enhances security and reusability.

💡 You might also like:

Use case example: Deploying a web server with an initialization script

Let's imagine you want to launch an AWS EC2 instance using Terraform and have it automatically install and start an NGINX web server at boot. Instead of embedding a long script directly into your Terraform file, you use the file() function to load a separate init.sh script.

resource "aws_instance" "web_server" {
  ami           = "ami-0c55b159cbfafe1f0"
  instance_type = "t2.micro"

  user_data = file("${path.module}/init.sh")
}
Enter fullscreen mode Exit fullscreen mode

init.sh

#!/bin/bash
yum update -y
yum install -y nginx
systemctl enable nginx
systemctl start nginx
echo "Hello from NGINX!" > /usr/share/nginx/html/index.html
Enter fullscreen mode Exit fullscreen mode

The file() function reads the contents of init.sh and passes it as user_data to the EC2 instance. On startup, the instance runs the script: it installs NGINX, starts it, and sets a welcome message. 

This method keeps your Terraform code clean, separates logic, and makes your setup more maintainable and modular.

Key points

Terraform's file() function reads a local file's content as a string. It's commonly used to inject shell scripts (e.g., EC2 user_data) or public keys into resources, helping keep code clean, modular, and easier to manage. Ideal for automating cloud resource configuration.

Terraform is really powerful, but to achieve an end-to-end secure GitOps approach, you need to use a product that can run your Terraform workflows. Spacelift takes managing Terraform to the next level by giving you access to a powerful CI/CD workflow and unlocking features such as:

  • Policies (based on Open Policy Agent)
  • Multi-IaC workflows
  • Self-service infrastructure
  • Integrations with any third-party tools

If you want to learn more about Spacelift, create a free account today or book a demo with one of our engineers.

Written by Mariusz Michalowski

Top comments (0)