This is part of an ongoing series of posts documenting the built-in interpolation functions in Terraform. For more information, check out the beginning post. In this post I am going to cover the trimspace() function. The example file is on GitHub here.
Function name: trimspace(string)
Returns: Takes a string and returns the string with any trailing whitespace removed
Example:
# Returns "String"
output "trimspace_output" {
value = "${trimspace("String ")}"
}
##############################################
# Function: trimspace
##############################################
##############################################
# Variables
##############################################
variable "trimspace" {
default = "A string with tab \t"
}
##############################################
# Resources
##############################################
##############################################
# Outputs
##############################################
output "1_trimspace_output" {
value = "${trimspace(var.trimspace)}"
}
output "2_length" {
value = "${length(var.trimspace)}"
}
output "3_length_trimspace" {
value = "${length(trimspace(var.trimspace))}"
}
Run the following from the trimspace folder to get example output for a number of different cases:
#Test with newline
$mystring = "String with one newline `n"
terraform apply -var "trimspace=$mystring"
#Just spaces
$mystring = " "
terraform apply -var "trimspace=$mystring"
#Empty String
terraform apply -var "trimspace="
#Spaces after newline
$mystring = "String with one newline `nNext line "
terraform apply -var "trimspace=$mystring"
Sanitized data is happy data! The same reasons you might want to use the chomp function apply to this function as well. Trailing spaces can reek havoc when that value is passed to another resource for use. Generally speaking, don’t trust anything from an end user or an outside data source.
It’s pretty hard to tell if the trimspace function has done anything, since the string looks the same in the output. I ended up using the length function to measure the string before and after trimspace was applied to make sure it was doing something. Fun fact, length says that it is only for lists, but it will give you the length of a string as well. I guess a string is just a list of characters after all. A tab and newline are also considered white space characters, but only if the newline is at the end of the string. Otherwise you’re not really at the end of the string are you? I tried passing the newline and tab characters from the command line with no success. That might be a consequence of using Windows. Instead I ended up storing the value in a PowerShell variable and then passing it to Terraform.
Coming up next is the upper() function.
Resourcely Guardrails and Blueprints
November 15, 2024
Deploying Azure Landing Zones with Terraform
November 12, 2024
October 18, 2024
What's New in the AzureRM Provider Version 4?
August 27, 2024