# Terraform Archive_File Data Source for Efficient Infrastructure as Code

Listen to this Post

When working with Terraform for Infrastructure as Code (IaC), you may need to upload archive files containing multiple items rather than individual files. A common use case is AWS Lambda deployments, where bundling code into a ZIP file is more efficient. Terraform’s `archive_file` data source helps automate this process while ensuring updates only occur when file contents change.

You Should Know: How to Use Terraform’s `archive_file`

1. Basic `archive_file` Example

The `archive_file` data source creates a ZIP file from specified sources. Below is a basic configuration:

[hcl]
data “archive_file” “lambda_zip” {
type = “zip”
source_dir = “${path.module}/lambda_code”
output_path = “${path.module}/lambda_function.zip”
}
[/hcl]

2. Hashing for Change Detection

Terraform uses file hashing to determine if the archive needs rebuilding. If no files change, Terraform skips recreating the ZIP.

[hcl]
output “archive_hash” {
value = data.archive_file.lambda_zip.output_base64sha256
}
[/hcl]

3. Using with AWS Lambda

Deploy the ZIP file to AWS Lambda efficiently:

[hcl]
resource “aws_lambda_function” “example” {
filename = data.archive_file.lambda_zip.output_path
function_name = “example_lambda”
role = aws_iam_role.lambda_role.arn
handler = “index.handler”
runtime = “nodejs14.x”
}
[/hcl]

4. Filtering Files in the Archive

Exclude unnecessary files (e.g., `node_modules`) using `excludes`:

[hcl]
data “archive_file” “lambda_zip” {
type = “zip”
source_dir = “${path.module}/lambda_code”
output_path = “${path.module}/lambda_function.zip”
excludes = [“node_modules/**”]
}
[/hcl]

5. Dynamic File Inclusion

Use `dynamic` blocks to conditionally include files:

[hcl]
dynamic “source” {
for_each = fileset(“${path.module}/lambda_code”, “*.js”)
content {
source_file = source.value
output_path = “js/${source.value}”
}
}
[/hcl]

6. Linux & Windows Commands for File Handling