DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Related

  • Python F-Strings
  • Java String: A Complete Guide With Examples
  • Generics in Java and Their Implementation
  • Sliding Window

Trending

  • Enhancing SQL Server Security With AI-Driven Anomaly Detection
  • Toward Indigenous AI: A Critical Analysis of BharatGen’s Role in Data Sovereignty and Language Equity
  • Data Storage and Indexing in PostgreSQL: Practical Guide With Examples and Performance Insights
  • AI's Cognitive Cost: How Over-Reliance on AI Tools Impacts Critical Thinking
  1. DZone
  2. Software Design and Architecture
  3. Cloud Architecture
  4. Converting List to String in Terraform

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.

By 
Mariusz Michalowski user avatar
Mariusz Michalowski
·
Jun. 11, 25 · Tutorial
Likes (1)
Comment
Save
Tweet
Share
1.5K Views

Join the DZone community and get the full member experience.

Join For Free

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:

Shell
 
variable "tags" {
  default = ["dev", "staging", "prod"]
}

output "tag_list" {
  value = join(", ", var.tags)
}


The output would be: 

Shell
 
"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.

Shell
 
variable "commands" {
  default = ["git pull", "npm install", "terraform apply -auto-approve"]
}

output "alias_command" {
  value = "alias deploy='${join(" && ", var.commands)}'"
}


Output:

Shell
 
"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:

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

Shell
 
variable "ports" {
  default = [22, 80, 443]
}

output "formatted_ports" {
  value = format("Allowed ports: %s", join(" | ", var.ports))
}


Output:

Shell
 
"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.

Shell
 
variable "tags" {
  default = ["dev", "staging", "prod"]
}

output "json_encoded" {
  value = jsonencode(var.tags)
}


Output:

Shell
 
"["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.

Data structure Strings Terraform (software)

Published at DZone with permission of Mariusz Michalowski. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Python F-Strings
  • Java String: A Complete Guide With Examples
  • Generics in Java and Their Implementation
  • Sliding Window

Partner Resources

×

Comments

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • [email protected]

Let's be friends: