Skip to content

Function chomp()

📝 Description

The chomp function removes newline characters (\n or \r\n) from the end of a string. If the string doesn't end with a newline, it leaves it unchanged.

Use Case: Essential when using the file() function to read SSH keys or scripts from disk, as these files often end with an invisible empty line that can break your configuration.


💻 Syntax

chomp(string)

💡 Examples

1. Cleaning a File Input:

# If your 'id_rsa.pub' has a hidden newline at the end:
# "ssh-rsa AAAAB3...user@host\n" -> Result: "ssh-rsa AAAAB3...user@host"
resource "aws_key_pair" "deployer" {
  key_name   = "deployer-key"
  public_key = chomp(file("${path.module}/id_rsa.pub"))
}

2. Basic Usage:

# Result: "hello"
output "clean_string" {
  value = chomp("hello\n\n")
}

⚠️ Key Detail

  • It only removes newlines from the end. If you have a newline in the middle of the string, it will stay there.

  • To remove other types of whitespace (like spaces or tabs), use the trimspace() function instead.


  • [[trimspace]] — Removes all types of whitespace from both ends.

  • [[trim]] — Removes custom characters from ends.

  • Official HashiCorp Docs