slide

Terraform fot d md5()

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

What is it?

Function name: md5(string)

Returns: Takes a string and returns the md5 hash of that string

Example:

# Returns 827ccb0eea8a706c4c34a16891f84e7b
output "md5_output" {
  value = "${md5("12345")}"
}

Example file:

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

variable "fileText" {
  default = "textFile.txt"
}

##############################################
# Resources
##############################################
##############################################
# Outputs
##############################################
output "md5_output" {
  value = "${md5(var.md5)}"
}

output "md5_file" {
  value = "${md5(file(var.fileText))}"
}

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


#Should return a26d69fa3acf4022a4505a0c823af393
terraform apply -var "md5=amanaplanacanalpanama"

#Should output 8D93AD635E2C8C822D796BD8726EEF6B
terraform apply -var "md5=ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"

#Empty string test give d41d8cd98f00b204e9800998ecf8427e (whut?)
terraform apply -var "md5="

Why use it?

There’s probably two good reasons to use this. If you’re downloading a file and want to verify its integrity, then you could calculate the md5 hash of the file and compare it to a hash supplied by the source. The other reason is that some resources require an md5 hash to be submitted along with a source file in order to validate a successful upload. An example would be the etag optional attribute on the aws_s3_bucket_object resource.

Lessons Learned

The function works as advertised. I provided an example where I pulled a file’s contents and calculated the md5 hash along with just doing it to a standard string. I think the file hash calculation is probably the more common of the two options. Funny thing is that running the md5 calculation with an “empty” string resulted in d41d8cd98f00b204e9800998ecf8427e. I don’t know how or why, but that’s cool I guess.

Coming up next is the pathexpand() function. You might wonder what happened to ’n’ and ‘o’. I guess there needs to be more functions!