Skip to content

Hash function for computing checksum of a directory #37579

@jackson-theisen

Description

@jackson-theisen

Terraform Version

Terraform v1.11.4
on darwin_arm64

Use Cases

In automated deployments, it's common to package and deploy entire directories (e.g. Lambda functions, Helm charts, etc.). A directory hash can act as a checksum to conditionally run a build for a given package.

Additionally, a directory hash could serve as a fingerprint for a directory to ensure no unexpected changes have occurred and the deployed version matches the intended version.

Attempted Solutions

I was able to solve for this by combining existing functions intended for individual files:

output "sha256" {
  description = "sha256 hash of the directory (sha256 of sha256 of each file in the directory recursively)"
  
  value = sha256(join("", [
    for file in fileset(var.directory, "**") :
    filesha256("${var.directory}/${file}")
  ]))
}

While the above solution works, it feels messy and isn't friendly from a human-readable perspective.

Proposal

The solution could look similar to the existing file hashing functions and would accept an argument for the path as well as an optional list of glob patterns to include/exclude from the calculation e.g. dirsha256(path, [patterns])

Example:

output "directory_hash" {
  value = dirsha256("lambda/my-function", ["!features/.*", "!tests/.*"])
}

References

None that I'm aware of

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions