0
0
TerraformHow-ToBeginner · 3 min read

How to Use the format Function in Terraform

In Terraform, the format function creates formatted strings by replacing placeholders with variable values. Use it like format("Hello %s", var.name) to insert variables into strings cleanly and readably.
📐

Syntax

The format function takes a format string with placeholders and a list of values to insert. Placeholders use % followed by a letter to specify the type, such as %s for strings or %d for integers.

Example placeholders:

  • %s: string
  • %d: integer
  • %f: floating-point number
terraform
format(format_string, value1, value2, ...)
💻

Example

This example shows how to use format to create a greeting message with a name and age.

terraform
variable "name" {
  default = "Alice"
}

variable "age" {
  default = 30
}

output "greeting" {
  value = format("Hello %s, you are %d years old.", var.name, var.age)
}
Output
greeting = "Hello Alice, you are 30 years old."
⚠️

Common Pitfalls

Common mistakes include:

  • Using the wrong placeholder type (e.g., %d for a string).
  • Not providing enough values for the placeholders.
  • Confusing format with string interpolation using ${}.

Always match placeholders to the correct value types and count.

terraform
/* Wrong: Using %d for a string */
output "wrong_example" {
  value = format("Name: %d", var.name)  # Error: var.name is string, %d expects integer
}

/* Right: Use %s for string */
output "right_example" {
  value = format("Name: %s", var.name)
}
📊

Quick Reference

PlaceholderDescription
%sString
%dInteger
%fFloating-point number
%%Literal percent sign

Key Takeaways

Use format() to build strings with placeholders replaced by variable values.
Match placeholder types (%s, %d, %f) to the correct variable types.
Provide the same number of values as placeholders in the format string.
format() improves readability over complex string interpolation.
Use %% to include a literal percent sign in the output string.