Converting List to String in Terraform
Use join(), format(), and jsonencode() in Terraform to name resources, format scripts/logs, and ensure clarity in dynamic configurations.
Join the DZone community and get the full member experience.
Join For FreeIn Terraform, you will often need to convert a list to a string when passing values to configurations that require a string format, such as resource names, cloud instance metadata, or labels. Terraform uses HCL (HashiCorp Configuration Language), so handling lists requires functions like join()
or format()
, depending on the context.
How to Convert a List to a String in Terraform
The join()
function is the most effective way to convert a list into a string in Terraform. This concatenates list elements using a specified delimiter, making it especially useful when formatting data for use in resource names, cloud tags, or dynamically generated scripts.
The join(", ", var.list_variable)
function, where list_variable
is the name of your list variable, merges the list elements with ", "
as the separator.
Here’s a simple example:
variable "tags" {
default = ["dev", "staging", "prod"]
}
output "tag_list" {
value = join(", ", var.tags)
}
The output would be:
"dev, staging, prod"
Example 1: Formatting a Command-Line Alias for Multiple Commands
In DevOps and development workflows, it’s common to run multiple commands sequentially, such as updating repositories, installing dependencies, and deploying infrastructure.
Using Terraform, you can dynamically generate a shell alias that combines these commands into a single, easy-to-use shortcut.
variable "commands" {
default = ["git pull", "npm install", "terraform apply -auto-approve"]
}
output "alias_command" {
value = "alias deploy='${join(" && ", var.commands)}'"
}
Output:
"alias deploy='git pull && npm install && terraform apply -auto-approve'"
Example 2: Creating an AWS Security Group Description
Imagine you need to generate a security group rule description listing allowed ports dynamically:
variable "allowed_ports" {
default = [22, 80, 443]
}
resource "aws_security_group" "example" {
name = "example_sg"
description = "Allowed ports: ${join(", ", [for p in var.allowed_ports : tostring(p)])}"
dynamic "ingress" {
for_each = var.allowed_ports
content {
from_port = ingress.value
to_port = ingress.value
protocol = "tcp"
cidr_blocks = ["0.0.0.0/0"]
}
}
}
The join()
function, combined with a list comprehension, generates a dynamic description like "Allowed ports: 22, 80, 443"
. This ensures the security group documentation remains in sync with the actual rules.
Alternative Methods
For most use cases, the join()
function is the best choice for converting a list into a string in Terraform, but the format()
and jsonencode()
functions can also be useful in specific scenarios.
1. Using format() for Custom Formatting
The format()
function helps control the output structure while joining list items. It does not directly convert lists to strings, but it can be used in combination with join()
to achieve custom formatting.
variable "ports" {
default = [22, 80, 443]
}
output "formatted_ports" {
value = format("Allowed ports: %s", join(" | ", var.ports))
}
Output:
"Allowed ports: 22 | 80 | 443"
2. Using jsonencode() for JSON Output
When passing structured data to APIs or Terraform modules, you can use the jsonencode()
function, which converts a list into a JSON-formatted string.
variable "tags" {
default = ["dev", "staging", "prod"]
}
output "json_encoded" {
value = jsonencode(var.tags)
}
Output:
"["dev", "staging", "prod"]"
Unlike join()
, this format retains the structured array representation, which is useful for JSON-based configurations.
Creating a Literal String Representation in Terraform
Sometimes you need to convert a list into a literal string representation, meaning the output should preserve the exact structure as a string (e.g., including brackets, quotes, and commas like a JSON array). This is useful when passing data to APIs, logging structured information, or generating configuration files.
For most cases, jsonencode()
is the best option due to its structured formatting and reliability in API-related use cases. However, if you need a simple comma-separated string without additional formatting, join()
is the better choice.
Common Scenarios for List-to-String Conversion in Terraform
Converting a list to a string in Terraform is useful in multiple scenarios where Terraform requires string values instead of lists. Here are some common use cases:
- Naming resources dynamically: When creating resources with names that incorporate multiple dynamic elements, such as environment, application name, and region, these components are often stored as a list for modularity. Converting them into a single string allows for consistent and descriptive naming conventions that comply with provider or organizational naming standards.
- Tagging infrastructure with meaningful identifiers: Tags are often key-value pairs where the value needs to be a string. If you’re tagging resources based on a list of attributes (like team names, cost centers, or project phases), converting the list into a single delimited string ensures compatibility with tagging schemas and improves downstream usability in cost analysis or inventory tools.
- Improving documentation via descriptions in security rules: Security groups, firewall rules, and IAM policies sometimes allow for free-form text descriptions. Providing a readable summary of a rule’s purpose, derived from a list of source services or intended users, can help operators quickly understand the intent behind the configuration without digging into implementation details.
- Passing variables to scripts (e.g., user_data in EC2 instances): When injecting dynamic values into startup scripts or configuration files (such as a shell script passed via
user_data
), you often need to convert structured data like lists into strings. This ensures the script interprets the input correctly, particularly when using loops or configuration variables derived from Terraform resources. - Logging and monitoring, ensuring human-readable outputs: Terraform output values are often used for diagnostics or integration with logging/monitoring systems. Presenting a list as a human-readable string improves clarity in logs or dashboards, making it easier to audit deployments and troubleshoot issues by conveying aggregated information in a concise format.
Key Points
Converting lists to strings in Terraform is crucial for dynamically naming resources, structuring security group descriptions, formatting user data scripts, and generating readable logs. Using join()
for readable concatenation, format()
for creating formatted strings, and jsonencode()
for structured output ensures clarity and consistency in Terraform configurations.
Published at DZone with permission of Mariusz Michalowski. See the original article here.
Opinions expressed by DZone contributors are their own.
Comments