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=stringdefault=" \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 ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access