How do you do simple string concatenation in Terraform?
String concatenation is a common task in Terraform, often used to dynamically construct resource names, tags, or other configuration values. Terraform provides several ways to concatenate strings, making it easy to handle various use cases.
Using Interpolation
The simplest way to concatenate strings in Terraform is by using interpolation. Interpolation allows you to embed variables and expressions directly into strings.
Example
variable "environment" {
default = "dev"
}
output "bucket_name" {
value = "my-app-${var.environment}-bucket"
}
Explanation
${var.environment}: Embeds the value of theenvironmentvariable into the string.- The resulting value will be
my-app-dev-bucketif theenvironmentvariable is set todev.
Using the join Function
The join function is another way to concatenate strings, especially when working with lists.
Example
variable "tags" {
default = ["Environment:Dev", "Team:Engineering"]
}
output "tags_string" {
value = join(", ", var.tags)
}
Explanation
join(", ", var.tags): Joins the elements of thetagslist into a single string, separated by a comma and a space.- The resulting value will be
Environment:Dev, Team:Engineering.
Best Practices
- Use interpolation for simple concatenation tasks.
- Use the
joinfunction for lists to improve readability and maintainability. - Avoid hardcoding values; use variables to make your configuration more flexible.
By understanding these techniques, you can efficiently handle string concatenation in Terraform and create dynamic, reusable configurations.
We earn commissions when you shop through the links below.
DigitalOcean
Cloud infrastructure for developers
Simple, reliable cloud computing designed for developers
DevDojo
Developer community & tools
Join a community of developers sharing knowledge and tools
SMTPfast
Developer-first email API
Send transactional and marketing email through a clean REST API. Detailed logs, webhooks, and embeddable signup forms in one dashboard.
QuizAPI
Developer-first quiz platform
Build, generate, and embed quizzes with a powerful REST API. AI-powered question generation and live multiplayer.
Want to support DevOps Daily and reach thousands of developers?
Become a SponsorFound an issue?
Related Posts
Also worth your time on this topic
How to Convert a List to a String in Terraform
Learn different methods for converting lists to strings in Terraform using join(), jsonencode(), and format() functions for various use cases.
Terraform State Management
What is Terraform state, why is it important, and how do you manage state in a team environment?
mid
Terraform Repository Structure Checklist
Best practices for organizing and structuring your Terraform projects for maintainability and scalability.
30-45 minutes