slide

Terraform fot d chomp()

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 chomp() function. The example file is on GitHub here.

What is it?

Function name: chomp(string)

Returns: Takes the string and removes any trailing newlines. Trailing in this case are any newline characters that are at the end of the string.

Example:

variable "chomp" {
  default = "A string with newlines \n\n\n\n"
}

# Returns "A string with newlines "
output "chomp" {
  value = "${chomp(var.chomp)}"
}

Example file:

##############################################
# Function: chomp
##############################################
##############################################
# Variables
##############################################
variable "chomp" {
  default = "A string with newlines \n\n\n\n\n"
}

##############################################
# Resources
##############################################
resource "local_file" "chomp_file" {
  content  = "${chomp(var.chomp)}"
  filename = "output.txt"
}

##############################################
# Outputs
##############################################
output "chomp_output" {
  value = "${chomp(var.chomp)}"
}

Run the following from the chomp folder to get example output for a number of different cases:

#Initialize for local_file resource
terraform init

#Create strings in PowerShell to test
$something = "String with one newline`n"
terraform apply -var "chomp=$something" -auto-approve

$something = "String with two newlines`n`n"
terraform apply -var "chomp=$something" -auto-approve

$something = "String with two lines`n Second line"
terraform apply -var "chomp=$something" -auto-approve

$something = "String with two lines`n Second line with newline `n"
terraform apply -var "chomp=$something" -auto-approve

#Just newlines
$something = "`n`n`n`n`n"
terraform apply -var "chomp=$something" -auto-approve

#Empty string
terraform apply -var "chomp="

Why use it?

As someone who has been bit before with trailing newlines in text files, the chomp function is great for cleaning up data pulled from potentially messy sources. If you know your text absolutely should not end in a newline, then chomp is your new best friend. Garbage in, garbage out as the old adage goes. While you’re at it, I would recommend cleaning up whitespace at the end of string, which is something chomp does not do.

Lessons learned

I found a fun bug! Let’s say you create a file using the local_file resource and populate it with a test string from a variable. Then you run the same config with an empty string as the value for the file. Terraform tries to run a diff to see if the contents of the file are different, and then it crashes. I submitted an issue so we’ll see what happens.

Coming up next is chunklist() which I hear is a favorite of sloth.