Heading to KubeCon North America 2025?

Meet with Spacelift 🚀

Terraform

How to Use Terraform Join & Split Functions with Strings

How to use the Terraform join and split functions

🚀 Level Up Your Infrastructure Skills

You focus on building. We’ll keep you updated. Get curated infrastructure insights that help you make smarter decisions.

Terraform employs the Hashicorp Configuration Language (HCL), which has several beneficial built-in functions. These functions can manipulate and transform values within a given expression. 

In this post, we will take a look at the operation of the join function and its counterpart, the split function for use with strings.

What we’ll cover:

  1. What is the Terraform join function?
  2. What does the Terraform join function do?
  3. Terraform join function use cases
  4. Terraform join examples
  5. What does the Terraform split function do?
  6. Terraform split examples

What is the Terraform join function?

The Terraform join function is a built-in function that allows you to concatenate a list of strings together. The join function is useful when you need to create a string from a list of elements and want to control the formatting of the resulting string.

join helps enforce naming consistency and avoids hardcoding repeated string patterns in Terraform modules or configurations. It is often used to create resource names, tags, or labels where multiple parts need to be combined in a specific format.

HCL does not support user-defined functions, like some other classic languages, for example, C or SQL. Only built-in functions are available for use with Terraform.

 

A particularly useful way to experiment with the operation of functions is to use the terraform console command. . To try it out, type terraform console on the command line, and then a simple join(", ", ["this", "and", "that"]) command. 

 

This provides an interactive console to the user. Note that terraform console does not require a state file to exist or be created first. If there is a remote state file in the current working directory, Terraform will read the state for the current Terraform workspace from the backend before evaluating any expressions.

What does the Terraform join function do?

The Terraform join function takes a list of strings and returns one string with the separator placed between each element.

The syntax for the join function is as follows:

join(delimiter, list)
  • delimiter: The string to be used between each pair of adjacent elements in the resulting string.
  • list: The list of elements to be concatenated.

If your list contains non-strings (numbers, bools, objects), convert them first (e.g., with tostring() or format()).

Terraform join function use cases

Terraform join is primarily useful when generating resource names, tags, or configuration strings from multiple values. Common use cases include:

  • Constructing resource names – Combine environment, application, and region into a consistent naming convention.
  • Building comma-separated strings for inputs – Used for parameters like CIDR block lists or security group rules.
  • Formatting tags or labels – Simplifies dynamic tag creation when multiple values need to be merged into one string.
  • IAM policy definitions – When defining actions or resources in IAM policies that require a string format, join() helps merge list values.
  • FQDN construction – Combine subdomain, environment, and domain to form full hostnames.
  • Concatenating subnet IDs for modules – When passing a list of subnet IDs into a module expecting a comma-separated string.

Terraform join examples

Let’s see some examples of using the join function in action:

Example 1. Joining two lists

Although people often say “join two lists,” join doesn’t merge lists together — it joins the elements of a single list into a string. 

In this example, the list ["this", "and", "that"] is turned into the string "this, and, that" by inserting ", " between each element:

join(", ", ["this", "and", "that"])

Results in the following output:

terraform join example

Example 2. Building a file path (or URL) from parts

Here, we construct a clean path string from separate pieces:

variable "env" {
  type    = string
  default = "prod"
}

locals {
  path_parts = ["srv", var.env, "nginx"]
}

output "config_path" {
  value = join("/", local.path_parts) # -> "srv/prod/nginx"
}

By keeping the parts in a list (local.path_parts) and joining with “/”, you avoid double slashes or fiddly string concatenation. 

The same pattern works for URLs (join("/", ["https://api.example.com", "v1", "users"])) or any other delimiter-separated string (like : for PATH-style values).

Example 3. Creating a resource tag

To create a resource tag using the join function in Terraform, concatenate multiple string values into a single tag value within the tags block. The join function combines list elements using a specified delimiter.

For example:

resource "aws_s3_bucket" "example" {
  bucket = "example-bucket"

  tags = {
    Name        = join("-", ["project", var.env, "bucket"])
    Environment = var.env
  }
}

Here, the join("-", ["project", var.env, "bucket"]) expression produces a tag value like "project-dev-bucket".

Example 4. Turning dynamic values into a comma-separated string

Providers and modules sometimes expect a single comma-separated string of values. If you have a list (perhaps gathered from resources or data sources), join converts it into the exact format required. 

# Imagine a module or resource that needs a CSV string of IPs
# (some providers/modules accept a single comma-separated string)
locals {
  app_ips = [
    "10.0.1.10",
    "10.0.1.11",
    "10.0.1.12",
  ]
}

output "ip_csv" {
  value = join(", ", local.app_ips) # -> "10.0.1.10, 10.0.1.11, 10.0.1.12"
}

If your elements aren’t strings (for example, numbers), you’d convert them first, e.g., join(", ", [for n in local.ports : tostring(n)]). This keeps your config clean and makes it easy to change the delimiter later without rewriting string concatenations.

Example 5. Joining Azure storage accounts

In the following example, we have three Azure storage accounts defined as lists of strings in the variable storage_account_names. We then use the join function in the outputs to show the outputted resource IDs in one comma-separated string.

provider "azurerm" {
 features = {}
}

# Define variables
variable "storage_account_names" {
 type    = list(string)
 default = ["storageaccount1", "storageaccount2", "storageaccount3"]
}

# Create Azure Storage Accounts
resource "azurerm_storage_account" "example" {
 count                    = length(var.storage_account_names)
 name                     = var.storage_account_names[count.index]
 resource_group_name      = "example-resource-group"
 location                 = "East US"
 account_tier             = "Standard"
 account_replication_type = "LRS"
}

# Join the resource IDs of the created storage accounts into a comma-separated string
output "joined_storage_account_ids" {
 value = join(", ", [for acc in azurerm_storage_account.example : acc.id])
}

The output would look like this:

joined_storage_account_ids = "/subscriptions/<subscription_id>/resourceGroups/example-re

What does the Terraform split function do?

Terraform split performs the opposite operation to Terraform join. It divides a string into a list of substrings using a specified delimiter. split returns a list where each element is a segment of the original string between instances of the delimiter.

Its syntax is:

split(delimiter, string)
  • delimiter – The character or sequence of characters used to split the string.
  • string – The full text that you want to divide.

Read more: How to Use Terraform Split Function

Terraform split examples

Here are some examples:

Example 1. Splitting a comma-separated string

The command below will split the three strings into a list:

split(", ", "this, and, that")

Terraform will process this by scanning the string for every occurrence of the delimiter ", ". Whenever it finds that pattern, it cuts the string at that point and creates a new element in the resulting list.

terraform console - split

The split function can be useful to use in output values when a list of values exists. 

Example 2: Splitting a path string

Terraform interprets the / as the boundary between directories in the given path string. Each substring between slashes becomes an element in the output list.

An Azure subnet ID typically looks like this:

/subscriptions/12345678-aaaa-bbbb-cccc-123456789abc/resourceGroups/my-rg/providers/Microsoft.Network/virtualNetworks/my-vnet/subnets/GatewaySubnet

This long string follows Azure’s Resource ID format, which uses slashes (/) to separate each part of the hierarchy.

So, for example, to create an Azure VNET gateway, the following configuration would split the gateway names with the “/” delimiter. 

The function call split("/", subnet_id) will divide the resource ID into a list of strings using / as the delimiter. The expression ends with [8], which means Terraform will extract the 9th element from the list (since indexing starts from 0).

output “gateway_network_name” {
value =    split(“/”,azurerm_virtual_network_gateway.azure_vng.ip_configuration[0].subnet_id)[8]
}

When Terraform evaluates the output block, the resulting value will be:

gateway_network_name = "my-vnet"

Note that split can be used with variables, for example:

split("/",var.VAR_NAME)

Key points

For more information, check out the official documentation.

Terraform is really powerful, but to achieve an end-to-end secure GitOps approach, you need to use a product that can run your Terraform workflows. Spacelift takes managing Terraform to the next level by giving you access to a powerful CI/CD workflow and unlocking features such as:

  • Policies (based on Open Policy Agent)
  • Multi-IaC workflows
  • Self-service infrastructure
  • Integrations with any third-party tools

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.

Manage Terraform better and faster

If you are struggling with Terraform automation and management, check out Spacelift. It helps you manage Terraform state, build more complex workflows, and adds several must-have capabilities for end-to-end infrastructure management.

Start free trial

Frequently asked questions

  • What are some best practices for using the join function?

    Proper use of join() improves code efficiency and readability in string handling operations. Best practices include:

    • Ensure all elements in the iterable are strings; convert non-string types using map(str, iterable) if needed.
    • Use a clear and consistent delimiter, for example ” “.join(words) for spaces or “,”.join(items) for CSV output.
    • Avoid using join() on very large iterables without need, as it constructs the full string in memory.
    • Keep readability in mind by formatting joins logically, such as “\n”.join(lines) for multi-line text.

     

  • What's the difference between join and string interpolation in Terraform?

    join(separator, list) explicitly concatenates elements of a list into a single string using a defined separator. String interpolation, written as “${…}”, embeds expressions or variables directly inside strings. For instance, “Hello ${var.name}” inserts the value of var.name into the string.

  • How do you do simple string concatenation in Terraform?

    In Terraform, simple string concatenation is done using interpolation syntax or the join() function. The most common approach is:

    “${var.prefix}-${var.name}”

    You can also use direct string literals with interpolation:

    “env-${var.environment}-service”

    Or use the join() function when combining multiple strings in a list:

    join(“-“, [“env”, var.environment, “service”])

    Terraform automatically handles type conversion for interpolated values.

Article sources

HashiCorp Developer | Terraform Docs. Functions – Configuration Language. Accessed: 22 October 2025

HashiCorp Developer | Terraform Docs. join Functions – Configuration Language. Accessed: 22 October 2025

HashiCorp Developer | Terraform Docs. split Functions – Configuration Language. Accessed: 22 October 2025

Terraform Functions Cheat Sheet

Grab our ultimate cheat sheet PDF for all
the Terraform functions you need on hand.

Share your data and download the cheat sheet