DEV Community

Cover image for Terraform String Template
Panchanan Panigrahi
Panchanan Panigrahi

Posted on

Terraform String Template

When working with Terraform, building dynamic infrastructure often requires flexibility in managing strings. Thatโ€™s where string templates come in. By using simple yet powerful templating techniques, you can inject variables, expressions, and even logic directly into strings. This not only reduces repetition but also enhances the readability and reusability of your configurations.

Letโ€™s explore String Templates

String Templates in Terraform

In Terraform, string templates enable you to embed expressions within a string using the ${} or %{} syntax. These templates allow you to dynamically generate strings by inserting values or performing operations directly inside the string.

Terraform offers two main methods for templating strings:

  1. Interpolation
  2. Directives

Letโ€™s explore each of these with examples:


1. Interpolation

Interpolation lets you embed variable values, resource attributes, or expressions directly into a string using the ${} syntax.

Simple Example:

variable "name" {
  default = "Terraform"
}

output "welcome_message" {
  value = "Welcome to ${var.name}!"
}
Enter fullscreen mode Exit fullscreen mode

In this example, ${var.name} inserts the value of the name variable into the string, producing the following output:

Welcome to Terraform!
Enter fullscreen mode Exit fullscreen mode

Multiline String Example:

Terraform also supports interpolation in multiline strings, which is useful when handling longer texts. This is done using the <<EOF syntax.

variable "environment" {
  default = "development"
}

output "deployment_notice" {
  value = <<EOF
    Deployment in progress...

    Environment: ${var.environment}
    Status: Successful!
  EOF
}
Enter fullscreen mode Exit fullscreen mode

In this case, the multiline string will interpolate ${var.environment}, generating the following output:

Deployment in progress...

Environment: development
Status: Successful!
Enter fullscreen mode Exit fullscreen mode

Using multiline strings with interpolation ensures you can handle more complex, readable outputs, especially when working with larger texts or configuration data.


2. Directives

Terraform's Directives offer greater flexibility than basic interpolation by using the %{} syntax to embed conditional logic and loops directly into string templates. There are two main types of string directives:

  1. If String Directive: Used for conditional statements within strings.
  2. For String Directive: Allows looping over a collection.

Let's dive into each with examples:


1. If String Directive

The if string directive is used to conditionally modify the content of a string based on boolean expressions. It supports %{if}, %{else}, and %{endif}.

Syntax:

%{if <BOOL>}
  // Conditional string content
%{else}
  // Fallback string content
%{endif}
Enter fullscreen mode Exit fullscreen mode

Example:

variable "environment" {
  default = "production"
}

output "plan_status" {
  value = <<-EOT
    %{ if var.environment == "production" }
    Warning: You are deploying to the production environment!
    %{ else }
    This is a safe deployment to a non-production environment.
    %{ endif }
  EOT
}
Enter fullscreen mode Exit fullscreen mode

In this example, Terraform checks the value of var.environment. If it's "production", the string will display a cautionary message; otherwise, a different message is shown:

Warning: You are deploying to the production environment!
Enter fullscreen mode Exit fullscreen mode

If var.environment was set to something else, like "development", the output would be:

This is a safe deployment to a non-production environment.
Enter fullscreen mode Exit fullscreen mode

2. For String Directive

The for string directive in Terraform provides a powerful way to iterate over collections (lists, sets, or maps) to generate repeated elements within strings, making your configurations more dynamic and efficient. This guide will cover its syntax, usage, and how to handle common pitfalls like unwanted whitespace.

Syntax Overview

The for string directive uses the following syntax to loop over items within a collection:

%{for <ITEM> in <COLLECTION>}
  // Repeated string content for each item
%{endfor}
Enter fullscreen mode Exit fullscreen mode
Step-by-Step Example: Creating Dynamic Greetings

Letโ€™s explore how to use this directive to create a personalized greeting for each member of a team.

variable "team_members" {
  default = ["Alice", "Bob", "Charlie"]
}

output "team_greetings" {
  value = <<-EOT
    Team members list:
    %{ for member in var.team_members }
    - Hello, ${member}!
    %{ endfor }
  EOT
}
Enter fullscreen mode Exit fullscreen mode

In this example:

  • We define a list variable team_members with values "Alice", "Bob", and "Charlie".
  • The for loop iterates over each member, appending a greeting to the output.

Output:

Team members list:
    - Hello, Alice!
    - Hello, Bob!
    - Hello, Charlie!
Enter fullscreen mode Exit fullscreen mode
The Whitespace Dilemma

You might notice the unintended leading spaces before each greeting. This happens because Terraform preserves the indentation from the code block, which can make your output look less tidy.

The Solution: Using the ~ Character

Terraform provides a handy ~ modifier to strip unwanted whitespace, giving your output a cleaner appearance.

output "team_greetings_stripped" {
  value = <<-EOT
    Team members list:
    %{ for member in var.team_members ~}
    - Hello, ${member}!
    %{ endfor ~}
  EOT
}
Enter fullscreen mode Exit fullscreen mode

By adding ~ at the end of %{ for ... ~} and %{ endfor ~}, you instruct Terraform to remove leading spaces, resulting in a polished output:

Output:

Team members list:
- Hello, Alice!
- Hello, Bob!
- Hello, Charlie!
Enter fullscreen mode Exit fullscreen mode

Final Thoughts

Incorporating string templates in Terraform elevates your configurations from static to dynamic, empowering you to manage complex infrastructure more efficiently. Whether you use interpolation to insert values or leverage directives for conditional logic and loops, string templates allow you to build flexible, adaptable systems. By mastering these techniques, you can write cleaner, more maintainable Terraform code that scales effortlessly with your needs.

Top comments (0)