Function format()
📝 Description
The format function produces a string by formatting a number of other values according to a specification string. It works similarly to the printf function in many programming languages.
Use Case: Perfect for generating standardized resource names, like
web-server-001,web-server-002, or building complex ARNs and connection strings.
💻 Syntax
-
spec: A string containing text and "verbs" (placeholders like
%s,%d). -
values: The data to plug into the placeholders.
💡 Common Verbs (Placeholders)
| Verb | Description |
|---|---|
%s |
Default format for strings. |
%d |
Default format for decimal integers. |
%t |
Default format for booleans (true/false). |
%03d |
Integer padded with zeros to 3 digits (e.g., 001). |
%% |
A literal percent sign. |
💡 Examples
1. Basic String Injection:
2. Zero-Padding for Resource Names (Very common):
Useful when you want your server names to be sorted correctly in the UI.
# Result: "server-001", "server-002", etc.
resource "aws_instance" "web" {
count = 3
tags = {
Name = format("server-%03d", count.index + 1)
}
}
3. Multiple Values:
# Result: "Env: production | Region: us-east-1"
output "info" {
value = format("Env: %s | Region: %s", var.env, var.region)
}
⚠️ Pro Tip
If you need to format a list of strings into a single string (like "a, b, c"), use the join() function instead. format() is better for structured, single-line templates.
🔗 Related Functions
-
[[join]] — Concatenate a list of strings.
-
[[upper]] / [[lower]] — Change case before formatting.