Terraform Templates
Terraform templates are a powerful feature that allows you to create dynamic and reusable configurations. Templates are often used to generate configuration files or scripts that need to be customized based on input variables or resource attributes. Terraform provides several ways to work with templates, primarily using the templatefile
function and the template
provider.
When to Use Templates
- Generating Dynamic Configurations: When you need to create configuration files or scripts that vary based on input parameters.
- Automation: When automating the generation of configuration files for software deployments, infrastructure setups, or other tasks.
- Reusability: To create reusable templates that can be applied across different environments or projects.
Methods for Working with Templates
- templatefile Function
- template Provider
Using the templatefile
Function
The templatefile
function is used to read a template file and render it with specified variables. This function is useful for generating configuration files or scripts dynamically.
Example: Using templatefile
to Generate a Configuration File
- Create a Template File
First, create a template file with placeholders for variables. For example, create a file named nginx.conf.tmpl
:
server {
listen 80;
server_name ${server_name};
location / {
proxy_pass http://${backend_server};
}
}
- Create a Terraform Configuration
Use the templatefile
function to render the template with variables. For example, create a file named main.tf
:
provider "aws" {
region = "us-east-1"
}
variable "server_name" {
default = "example.com"
}
variable "backend_server" {
default = "127.0.0.1:8080"
}
data "template_file" "nginx_config" {
template = file("${path.module}/nginx.conf.tmpl")
vars = {
server_name = var.server_name
backend_server = var.backend_server
}
}
resource "local_file" "nginx_config" {
content = data.template_file.nginx_config.rendered
filename = "${path.module}/nginx.conf"
}
output "nginx_config" {
value = data.template_file.nginx_config.rendered
}
3.Initialize and Apply the Configuration
terraform init
terraform apply
After running these commands, Terraform will generate an nginx.conf
file with the specified variables replaced.
Using the template
Provider
The template
provider allows for more complex template rendering within Terraform. It can be used to manage configuration files, scripts, and other text files that require dynamic content.
Example: Using the template
Provider to Generate a Script
- Create a Template File
Create a template file named startup_script.sh.tmpl
:
#!/bin/bash
echo "Starting server ${server_name} on port ${port}"
- Create a Terraform Configuration
Use the template
provider to render the template with variables. For example, create a file named main.tf
:
provider "aws" {
region = "us-east-1"
}
provider "template" {}
variable "server_name" {
default = "example-server"
}
variable "port" {
default = "8080"
}
data "template_file" "startup_script" {
template = file("${path.module}/startup_script.sh.tmpl")
vars = {
server_name = var.server_name
port = var.port
}
}
resource "local_file" "startup_script" {
content = data.template_file.startup_script.rendered
filename = "${path.module}/startup_script.sh"
}
output "startup_script" {
value = data.template_file.startup_script.rendered
}
3.Initialize and Apply the Configuration
terraform init
terraform apply
After running these commands, Terraform will generate a startup_script.sh
file with the specified variables replaced.
Advanced Example: Combining Templates and Resources
Here’s an example of using a template to configure an AWS EC2 instance with a custom user data script:
- Create a Template File for User Data
Create a file named user_data.sh.tmpl
:
#!/bin/bash
echo "Hello, ${username}!" > /var/www/html/index.html
- Create a Terraform Configuration
Create a file named main.tf
:
provider "aws" {
region = "us-east-1"
}
variable "username" {
default = "TerraformUser"
}
data "template_file" "user_data" {
template = file("${path.module}/user_data.sh.tmpl")
vars = {
username = var.username
}
}
resource "aws_instance" "web" {
ami = "ami-0c55b159cbfafe1f0"
instance_type = "t2.micro"
user_data = data.template_file.user_data.rendered
tags = {
Name = "web-server"
}
}
output "user_data" {
value = data.template_file.user_data.rendered
}
This configuration will create an EC2 instance with a custom user data script that writes a welcome message to the instance.
Terraform templates allow you to create dynamic and reusable configurations by integrating variables into text files. Using the templatefile
function or the template
provider, you can generate configuration files, scripts, and other text files with dynamic content based on input variables. This approach enhances automation, reusability, and flexibility in managing infrastructure configurations with Terraform.
official link –https://developer.hashicorp.com/terraform/language/functions/templatefile
Example
variable "software" {
default = "nginx"
}
data "template_file" "user_data" {
template = file("user_data.tpl")
vars = {
software = var.software
}
}
resource "aws_instance" "example" {
ami = "ami-0c55b159cbfafe1f0"
instance_type = "t2.micro"
user_data = data.template_file.user_data.rendered
}
template file
#!/bin/bash
sudo apt-get update
sudo apt-get install -y {{ .software }}
List 10 real use case where i can use Template template_file of Terrraform
- Cloud-init Configuration: You can use Terraform’sÂ
template_file
 data source to create cloud-init configuration files for your virtual machines or instances. - Nginx Configuration: WithÂ
template_file
, you can create an Nginx configuration file to customize the web server based on your specific needs. - DNS Records:Â UseÂ
template_file
 to create custom DNS records and add them to your DNS server configuration files. - Configuration Files for Services:Â
template_file
 can be used to generate configuration files for various services such as Apache, MySQL, Postgres, etc. - SSL/TLS Certificates: You can useÂ
template_file
 to generate SSL/TLS certificate configuration files for various web servers. - Bash Scripts: UseÂ
template_file
 to generate bash scripts to automate repetitive tasks such as backing up files or deploying code. - User Data for EC2 Instances: WithÂ
template_file
, you can create EC2 instance user data scripts to configure your instances when they launch. - Load Balancer Configuration:Â You can useÂ
template_file
 to create load balancer configuration files for services like AWS Elastic Load Balancer (ELB) or NGINX. - Kubernetes Manifests:Â
template_file
 can be used to create Kubernetes manifest files for deploying applications to a Kubernetes cluster. - Database Configuration Files: UseÂ
template_file
 to generate database configuration files for various databases like MongoDB, Redis, Cassandra, etc.