Terraform – FotD – urlencode()

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

What is it?

Function name: urlencode(string)

Returns: Takes a string and returns the a URL-safe copy of the string.

Example:

variable "string" {
  default = "My Text"
}

# Returns "My+Text"
output "urlencode_output" {
  value = "${urlencode(var.string)}"
}

Example file:

##############################################
# Function: urlencode
##############################################
##############################################
# Variables
##############################################
variable "urlencode" {}

##############################################
# Resources
##############################################
##############################################
# Outputs
##############################################
output "urlencode_output" {
  value = "${urlencode(var.urlencode)}"
}

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

#We have to get something to encode first
$fileContent = Get-Content .\textFile.txt

terraform apply -var "urlencode=$fileContent"

#Test out some special characters
terraform apply -var "urlencode=Here's a string:  Bistromatically speaking I have a $40 check, with 20% gratuity, (don't forget the -2^e for service) & #1 for good measure."

#More fun
$testString = 'HI!@#$%^&*()_+-=;,./?\|`~BYE'
terraform apply -var "urlencode=$testString"

#Empty string test
terraform apply -var "urlencode="

Why use it?

Better safe than sorry I always say. If you’re trying to hit up a URL using the HTTP or External providers, it’s probably best to sanitize that input first. The urlencode function will do exactly that.

Lessons Learned

My first question when I read the official docs was, “What is a URL-safe string?” As always the answer is to check Wikipedia. The actual standard that appears to be in use is the application/x-www-form-urlencoded standard. You can tell since the space character is encoded as a + instead of the more common %20. I suppose this makes it safe for use in form data submissions as well.

Coming up next is the uuid() function.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.