In 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.
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.
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 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.
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.
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.
- Tagging infrastructure with meaningful identifiers.
- Improving documentation via descriptions in security rules.
- Passing variables to scripts (e.g.,
user_data
in EC2 instances). - Logging and monitoring, ensuring human-readable outputs.
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.
We encourage you to explore how Spacelift makes it easy to work with Terraform. If you need help managing your Terraform infrastructure, building more complex workflows based on Terraform, and managing AWS credentials per run, instead of using a static pair on your local machine, Spacelift is a fantastic tool for this.
If you want to learn more about Spacelift, create a free account today or book a demo with one of our engineers.
Note: New versions of Terraform are placed under the BUSL license, but everything created before version 1.5.x stays open-source. OpenTofu is an open-source version of Terraform that expands on Terraform’s existing concepts and offerings. It is a viable alternative to HashiCorp’s Terraform, being forked from Terraform version 1.5.6.
Terraform management made easy
Spacelift effectively manages Terraform state, more complex workflows, supports policy as code, programmatic configuration, context sharing, drift detection, resource visualization and includes many more features.