Managing strings in Terraform: A comprehensive guide

Managing strings in Terraform can be a bit tricky, but with the right techniques and tools, it can be done with ease.

One of the most important things to keep in mind when working with strings in Terraform is to properly format them. This means using proper indentation, spacing, and line breaks to make the code more readable and easier to understand.

Additionally, you should also use quotes around strings to ensure that they are interpreted correctly by Terraform.

Another important technique for managing strings in Terraform is to use variables. Variables allow you to store and reuse string values throughout your Terraform code, making it easier to manage and update your infrastructure. For example, you can use variables to store the names of your resources or the values of your inputs, and then reference them throughout your code.

Example: Variable named greeting_msg containing a string text message

1variable "greeting_msg" {
2  default = ["Hello! How are you?"]
3}
4
5output "greeting_message" {
6  value = format("%s", var.greeting_msg)
7}  

You can also use functions to manipulate strings in Terraform. For example, you can use the "concat" function to combine two or more strings together, or the "length" function to determine the number of characters in a string. These functions can be useful for creating dynamic strings that change based on the values of your variables or other inputs.

This is a comprehensive guide on handling the strings in Terraform. In this guide, we will go through the following functions for handling the string in a better way -

  1. How to do multiple Strings concatenation in Terraform?
  2. How to concate numbers with string in Terraform?
  3. Remove newline characters from the end of a string?
  4. How to check the if string ends with?
  5. How to format the string in Terraform?
  6. Combine a list of strings into a single string using formatlist() function?
  7. How to add a specified number of spaces to the beginning of each line in a string?
  8. How to join a list of strings into a single string, with a specified separator
  9. How to convert a string to lowercase and uppercase?
  10. How to use the REGEX function in terraform?
  11. How to replace String in Terraform?
  12. How to split string in Terraform?
  13. How to check if the string contains a substring in terraform using startswith?
  14. How to reverse the string in Terraform?
  15. How to use substr in Terraform?
  16. How to convert a string into a title in Terraform?
  17. How to use Terraform trim(), trimprefix(), trimsuffix(), trimspace()?

1. How to do String concatenation in Terraform?

String concatenation is the process of joining two or more strings together to form a single, combined string. In Terraform you can use format() function to join/concatenate the strings.

Example

 1variable "first-name" {
 2  default = "Rahul"
 3}
 4
 5variable "last-name" {
 6  default = "Wagh"
 7}
 8
 9output "formatted_string" {
10  value = "${format("My first name is %s and my last name is %s", var.first-name, var.last-name)}"
11}

Terraform concate mulitple string

2. How to concate numbers with string in Terraform?

Along with string concatenation, you can even concate the numbers with string also.

Example

 1 variable "first-name" {
 2  default = "Rahul"
 3}
 4
 5variable "last-name" {
 6  default = "Wagh"
 7}
 8
 9variable "age" {
10  default = 33
11}
12
13output "formatted_string" {
14  value = "${format("My first name is %s and my last name is %s and my age is %d", var.first-name, var.last-name, var.age)}"
15}

Terraform concate string and number


3. Remove newline characters from the end of a string?

The next function which we are going to see is for removing the new line character from the end of the string. Terraform provides chomp fucntion for removing the characters at the end of a string.

Example

1#following variable contains a new line character
2variable "first-name-with-extra-char" {
3  default = "Rahul\n"
4}
5
6output "formatted_string" {
7  value = chomp(var.first-name-with-extra-char)
8}

Terraform Remove newline characters from the end of a string


4. How to check the if string endswith?

Terraform has an in-built function called at endswith which can help you to check if the string ends with a matching string. The function returns boolean based on the check.

If the match is found and the string ends with the desired match then it will return true otherwise it will return false.

1variable "full-name" {
2  default = "Rahul Wagh"
3}
4
5output "formatted_string" {
6  value = endswith(var.full-name, "Wagh")
7}

Terraform check the if string endswith


5. How to format the string in Terraform?

In terraform you can use format() function to provide formatting to string, number.

Also, you can use the format() function to concate the strings in Terraform .

Example

 1 variable "first-name" {
 2  default = "Rahul"
 3}
 4
 5variable "last-name" {
 6  default = "Wagh"
 7}
 8
 9variable "age" {
10  default = 33
11}
12
13output "formatted_string" {
14  value = "${format("My first name is %s and my last name is %s and my age is %d", var.first-name, var.last-name, var.age)}"
15}

Terraform concate mulitple string


6. Combine a list of strings into a single string using formatlist() function.

Terraform's formatlist() function allows you to combine a list of strings into a single string, with a specified separator.

For example, if you have a list of strings ["apple", "banana", "orange"] and you want to combine them into a single string with a separator of ", ", you would use the following format:

Example

1variable "fruit-list" {
2  default = ["apple", "banana", "orange"]
3}
4
5output "formatted_string" {
6  value = formatlist("%s, ", var.fruit-list)
7} 

Terraform formatlist

The output would be "apple, banana, orange".

Note that the separator is specified as the first argument to the formatlist function, followed by the list of strings you want to combine.


7. How to add a specified number of spaces to the beginning of each line in a string?

The indent function in Terraform is used to add a specified number of spaces to the beginning of each line in a string. This is useful for formatting multi-line strings in a consistent and readable way.

Example with indent function

1variable "my-fruit-list" {
2  default = "[\n  foo,\n  bar,\n]\n"
3}
4
5output "formatted_string" {
6  value = indent(2,var.my-fruit-list)
7}

with indent fucntion

Example without indent function

1variable "my-fruit-list" {
2  default = "[\n  foo,\n  bar,\n]\n"
3}
4
5output "formatted_string" {
6  value = var.my-fruit-list
7}

without indent fucntion


8. How to join a list of strings into a single string, with a specified separator?

The join function in Terraform is used to join a list of strings into a single string, with a specified separator. This is useful for combining a list of items into a single string that can be used in a resource configuration.

For example, if you have a list of strings ["apple", "banana", "orange"] and you want to combine them into a single string with a separator of ", " you would use the following format:

The output would be "apple,banana,orange"

Example

1variable "list" {
2  default = ["apple", "banana", "orange"]
3}
4
5output "joined_string" {
6  value = "${join(", ", var.list)}"
7}

Terraform join on the list


9. How to convert string to lowercase and uppercase?

The lower and upper functions in Terraform are used to convert a string to lowercase or uppercase, respectively.

The [lower function][19] takes a single argument, which is the string that you want to convert to lowercase and returns the lowercase version of the string.

Similarly, the [upper function][20] takes a single argument, which is the string that you want to convert to uppercase and returns the uppercase version of the string.

 1variable "string_1" {
 2  default = "--this is lower case string--"
 3}
 4
 5variable "string_2" {
 6  default = "--THIS IS UPPER CASE STRING--"
 7}
 8
 9output "joined_string" {
10  value = format("%s \n %s",upper(var.string_1),lower(var.string_2))
11} 

how to user lower and upper function in terraform

You can use these functions in various cases, for example, to make sure that the case of the string is consistent throughout your Terraform code, or to convert the case of a string before comparing it to another string.

1resource "aws_s3_bucket" "example" {
2  bucket = "EXAMPLE-BUCKET"
3  tags = {
4    Name = "example-bucket"
5    Bucket_Case = upper(var.bucket_name)
6  }
7}

10. How to use the REGEX function in terraform?

Terraform does provide support for the REGEX and you can use the power of REGEX inside your terraform project to perform some validation and complex check.

Here is the syntax for using the REGEX inside terraform -

1regex(pattern, string)

Here are the key points on how to use the regex -

  1. pattern- You must define the pattern for the REGEX, for example, if you want to perform the email validation then you must write the REGEX for email validation.
  2. string- Here you need to pass the string on which you want to perform the validation.

Regex Example for Email Validation-

1
2variable "email" {
3  default = "user@example.com"
4}
5
6output "is_valid_email" {
7  value = "${regex("^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$", var.email)}"
8} 

Here are the key points about the capture group in the regex -

  1. No Capture group- If the pattern has no capturing group the result will be the substring matched by the pattern
  2. One or more Capture groups- If the pattern has one or more unnamed capture groups the result will be the list of captured substrings in the same order as the definition of the capture groups.
  3. One or more named capture groups- If the pattern has one or more named capture groups the result will be the list of captured substrings, using the capture group names as map keys.

11. How to replace String in terraform?

In Terraform, the replace function can be used to replace all occurrences of a substring within a given string with a new substring.

The syntax for the replace function is as follows:

1replace(string, substring_to_replace, new_substring) 

Example

 1variable "example_string" {
 2  default = "hello world"
 3}
 4
 5locals {
 6  replaced_string = replace(var.example_string, "world", "Terraform")
 7}
 8
 9output "replaced_string" {
10  value = local.replaced_string
11}

In this example, the replace function is used to replace the substring "world" in the variable example_string with the new substring "Terraform". The resulting string is then stored in a local variable called replaced_string, which is then outputted.

Output:

1replaced_string = "hello Terraform" 

12. How to split string in Terraform?

The split function can be used to split a string into a list of substrings based on a given delimiter. This is useful for working with strings that contain multiple values or for converting a comma-separated string into a list.

1split(delimiter, string)

Example-

 1variable "example_string" {
 2  default = "one,two,three,four"
 3}
 4
 5locals {
 6  string_list = split(",", var.example_string)
 7}
 8
 9output "string_list" {
10  value = local.string_list
11}

Here is the output:

1string_list = [  "one",  "two",  "three",  "four",]

13. How to check if the string contains a substring in terraform using startswith?

The startswith function in Terraform can be used to find a substring in a string. Here is the syntax of startswith

1startswith(string, prefix)

Here is a very basic example showcasing how to find sub-string hello inside a string hello world

 1variable "example_string" {
 2  default = "hello world"
 3}
 4
 5locals {
 6  starts_with_hello = startswith(var.example_string, "hello")
 7}
 8
 9output "starts_with_hello" {
10  value = local.starts_with_hello
11}

Output

1starts_with_hello = true

14. How to reverse the string in Terraform?

The strrev function takes a string as input and returns the string with its characters in reverse order.

The syntax for the reverse function is as follows:

1strrev(string) 

Example showcasing how to reverse a string hello -

 1variable "example_string" {
 2  default = "hello world"
 3}
 4
 5locals {
 6  reversed_string = strrev(var.example_string)
 7}
 8
 9output "reversed_string" {
10  value = local.reversed_string
11}
12 

Output

1 reversed_string = "dlrow olleh"

15. How to use substr in Terraform?

The substr function can be used to extract a substring from a given string. You can specify the starting position and the length of the substring to extract.

1substr(string, starting_position, length) 

Example with substr -

 1variable "example_string" {
 2  default = "hello world"
 3}
 4
 5locals {
 6  substring = substr(var.example_string, 1, 5)
 7}
 8
 9output "substring" {
10  value = local.substring
11}

Output

1substring = "hello" 

16. How to convert the string into a title in Terraform?

Terraform provides a title function to convert a string into the title by converting the first letter of the string to upper case.

Here is an example showcasing the use of title function -

1variable "example_string" {
2  default = "hello world"
3}
4
5output "substring" {
6  value = title(var.example_string)
7}

Output-

1Hello World 

17. How to use Terraform trim(), trimprefix(), trimsuffix(), trimspace()?

Terraform provides 4 types of trim functions. But each trim function has a different purpose. Let's see each one of those in a bit more detail -

1. trim()- The trim() fucntion will remove the set of string from the beginning as well as end of string.

Example: - In this example, we will remove the ! character from the beginning as well as from the end of the screen.

1variable "example_string" {
2  default = "!hello world!"
3}
4
5output "substring" {
6  value = trim(var.example_string, "!")
7}

Output-

1hello world 

2. trimprefix()- As the name suggest the trimprefix() will trim the string from the beginning. Here is an example -

1 variable "example_string" {
2  default = "!hello world!"
3}
4
5output "substring" {
6  value = trim(var.example_string, "!hello")
7}

Output-

1world! 

3. trimsuffix()- As in the previous example we have seen some trim() functions but the trimsuffix() will be used for removing the string from the end.

Here is an example -

1variable "example_string" {
2  default = "!hello world!"
3}
4
5output "substring" {
6  value = trimsuffix(var.example_string, "world!")
7}

Output-

1!hello

4. trimspace()- This trimspace() function will be used to remove the spaces from the string, so if you have any space in string variables then you can use the trimspace() function.

Here is an example -

1variable "example_string" {
2  default = "!hello world!"
3}
4
5output "substring" {
6  value = trimspace(var.example_string)
7}

Output-

1!helloworld!

Want to learn more about then click here - Terraform Escape Sequences

Posts in this Series