如何基于源内容校验和设置Terraform的output_path以更新Lambda包?
Terraform AWS Canary代码更新问题:基于内容校验和自动触发变更
问题背景
使用Terraform管理AWS Synthetics Canary(或Lambda)时,存在一个常见问题:除非压缩包的文件名发生变化,否则Terraform无法识别代码内容已更新,导致新的代码无法自动部署到Canary中。
解决方案思路
核心是让归档文件的文件名随代码内容自动变化——通过计算渲染后代码内容的MD5校验和,将其嵌入到输出文件名中。只要代码内容改变,MD5值就会变化,文件名随之更新,Terraform就能检测到变更并重新生成归档、更新Canary。
修改后的Terraform代码
locals { # 预渲染所有Canary的代码内容,避免重复计算 canary_contents = { for endpoint_key, endpoint_val in var.endpoints : endpoint_key => templatefile("${path.module}/canary-lambda.js.tpl", { endpoint = endpoint_val.url }) } # 计算每个渲染后内容的MD5校验和 canary_content_md5 = { for endpoint_key, content in local.canary_contents : endpoint_key => md5(content) } } data "archive_file" "canary_archive_file" { for_each = var.endpoints type = "zip" # 将MD5校验和加入输出文件名,内容变化则文件名自动更新 output_path = "${path.module}/tmp/${each.key}-${local.canary_content_md5[each.key]}.zip" source { content = local.canary_contents[each.key] filename = "nodejs/node_modules/index.js" } }
代码说明
- 预渲染内容:通过
local.canary_contents提前渲染所有endpoint对应的模板代码,避免在archive_file中重复执行templatefile计算。 - 生成MD5校验和:利用Terraform内置的
md5()函数,对每个渲染后的代码内容计算哈希值,得到唯一标识内容的MD5字符串。 - 动态生成文件名:将MD5值作为输出文件名的一部分,比如
api-endpoint-d41d8cd98f00b204e9800998ecf8427e.zip。只要代码内容有任何修改,MD5值就会改变,文件名也会跟着变。 - 触发Terraform变更:文件名变化后,Terraform会识别到
archive_file的输出路径已更新,重新生成压缩包,并自动触发aws_synthetics_canary资源的更新,部署新的代码。
内容的提问来源于stack exchange,提问作者hendry
相关产品推荐
相关产品推荐

