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.
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)}"
}
##############################################
# 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="
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.
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.
Vault Provider and Ephemeral Values
July 21, 2025
Write-only Arguments in Terraform
July 15, 2025
July 1, 2025
On HashiCorp, IBM, and Acceptance
March 3, 2025