Terraform – FotD – base64decode()

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 base64decode() function. The example files are on GitHub here.

What is it?

Function name: base64decode(string)

Returns: The base64decode function returns a decoded value of a base64 encoded string.

Example:

variable "base64decode" {
  default = "MTIzNA=="
}

# Returns 1234
output "base64decode" {
  value = "${base64decode(var.base64decode)}"
}

Example file:

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

##############################################
# Resources
##############################################
##############################################
# Outputs
##############################################
output "base64decode_output" {
  value = "${base64decode(var.base64decode)}"
}

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

#We have to encode something first
$fileContent = get-content .\terraform_image.png
$fileContentBytes = [System.Text.Encoding]::UTF8.GetBytes($fileContent)
$fileContentEncoded = [System.Convert]::ToBase64String($fileContentBytes)

terraform apply -var "base64decode=$fileContentEncoded"

#Should output ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789
terraform apply -var "base64decode=QUJDREVGR0hJSktMTU5PUFFSU1RVVldYWVowMTIzNDU2Nzg5"

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

Why use it?

If you are being handed a string that is base64 encoded by a web service or some other data source, this is how you can transform it back into a usable string for the rest of the application. I would think primarily of parsing URL strings that are base64 encoded to assist with data transfer. If you are using the HTTP Provider to query information from a site, then you might use this function.

Lessons learned

I have to be honest here, I didn’t really know anything about base64 encoding before I started learning about this function. In that regard, it was an excellent learning experience. If you want to know more about base64 encoding, I definitely recommend reading through the Wikipedia article.

Coming up next is base64encode().

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.