Terraform: Use a useful unique zip-name based on a md5 checksum

Often times, a unique filename is needed for use in Terraform. We usually create resource "random_string".

resource "random_string" "random" {
  length = 5
  special = false
}

data "archive_file" "lambda" {
  type        = "zip"
  source_file = "lambda.py"
  output_path = "lambda-${random_string.random.result}.zip"
}

I think it is a good idea to include the hash (md5 checksum) of its contents in the name of the archive. Then you can verify if the file content is compatible with the archive without having to unpack it.

Like this:

$ cat lambda.tf

locals {
  source_file = "lambda.py"
  hash        = substr(filemd5(local.source_file), 0, 6)
}

data "archive_file" "lambda" {
  type        = "zip"
  source_file = local.source_file
  output_path = "lambda-${local.hash}.zip"
}

Then after terraform plan you will have a new zip-file with a hash in the name.

$ k                                 # have you already tried "k"?
total 32
-rw-r--r-- 1 loop staff 1476  6 Apr   20:52   lambda-11788a.zip 
-rw-r--r-- 1 loop staff  239  6 Apr   20:53   lambda.tf 
-rw-r--r-- 1 loop staff 4124  6 Apr   20:30   lambda.py 

$ md5sum lambda.py
11788a6ee7c73ea73b17f372e4d49750  lambda.py

$ md5sum lambda.py | cut -c1-6
11788a

When you check the lambda.py file, you can see that the output matches the name of the zip file.

This way I can be sure that the file in the archive (which probably landed somewhere in the cloud and is not in the git repository) matches the local source.

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.