slide

Terraform fot d trimspace()

Ned Bellavance
2 min read

Cover

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.

What is it?

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   ")}"
}

Example file:

##############################################
# 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"

Why use it?

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.

Lessons Learned

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.