Chapter 3. Terraform Syntax Patterns

Terraform functions give users the flexibility and power to manipulate data within their configuration files. They facilitate data transformation, perform arithmetic, and aid in working with complex data types such as lists, maps, and objects. They allow users to construct more dynamic and adaptable Terraform configurations at their core.

3.1 Cleaning User Inputs with trimspace

Problem

While creating infrastructure using Terraform, user inputs often need to be processed for extra whitespace, newlines, or other unexpected characters. This can lead to errors or inconsistencies in resource creation if not correctly handled. Therefore, knowing how to clean user inputs using Terraform’s built-in functions like chomp and trimspace is essential.

Solution

Establish a robust foundation for input sanitization by introducing a dedicated variable, which will be the target for applying the trimspace function:

variable "user_input" {
  description = "The user input that needs cleaning"
  type = string
  default = " \nExample user input with leading and trailing spaces\n "
}

locals {
  clean_user_input = trimspace(var.user_input)
}

output "clean_user_input" {
  value = local.clean_user_input
}

Discussion

In this code snippet, we are declaring a variable named user_input. This will serve as our raw, unprocessed input from the user. It’s set with a default value that includes leading and trailing whitespace and newlines for demonstration.

Next, we define a ...

Get Terraform Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.