DEV Community

Spacelift team for Spacelift

Posted on β€’ Originally published at spacelift.io

1

Converting List to String in Terraform

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.

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)
}
Enter fullscreen mode Exit fullscreen mode

The output would be:

 

"dev, staging, prod"
Enter fullscreen mode Exit fullscreen mode

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)}'"
}
Enter fullscreen mode Exit fullscreen mode

Output:

"alias deploy='git pull && npm install && terraform apply -auto-approve'"
Enter fullscreen mode Exit fullscreen mode

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"]
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

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.

πŸ’‘ You might also like:

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 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))
}
Enter fullscreen mode Exit fullscreen mode

Output:

"Allowed ports: 22 | 80 | 443"
Enter fullscreen mode Exit fullscreen mode

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)
}
Enter fullscreen mode Exit fullscreen mode

Output:

"["dev", "staging", "prod"]"
Enter fullscreen mode Exit fullscreen mode

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.
  • 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.

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.

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.

Written by Mariusz Michalowski

Top comments (0)