在Terraform中,如何避免null_resource脚本未执行时触发依赖步骤?
问题分析与解决方案
你的核心问题在于:depends_on仅控制执行顺序,无法实现条件执行。null_resource仅在triggers关联的文件内容变化时,才会重新执行local-exec脚本;但archive_file作为数据源,每次terraform plan/apply都会自动刷新,和null_resource是否执行无关。
以下是两种可行的解决思路:
方案一:将压缩逻辑整合到构建脚本中
直接在create_pkg.sh末尾添加压缩命令,让压缩步骤仅在null_resource触发执行时运行,彻底省去单独的archive_file数据源。
修改create_pkg.sh示例:
# 原脚本的构建逻辑(安装依赖、拷贝文件等) # ... # 添加压缩步骤 zip -r "${output_path}" "${path_cwd}/${dir_name}/"
同时在Terraform的null_resource环境变量中传递output_path:
resource "null_resource" "lambda_buildstep" { triggers = { handler = base64sha256(file("lambda_function/lambda_function.py")) requirements = base64sha256(file("lambda_function/requirements.txt")) script = base64sha256(file("scripts/create_pkg.sh")) } provisioner "local-exec" { command = "bash ${path.module}/scripts/create_pkg.sh" environment = { source_code_path = var.path_source_code function_name = var.function_name path_module = path.module runtime = var.runtime path_cwd = path.cwd dir_name = var.distribution_pkg_folder output_path = var.output_path # 新增:传递压缩输出路径 } } }
最后移除Terraform代码中的data "archive_file" "create_dist_pkg"块。
方案二:让archive_file依赖null_resource的重建状态
利用null_resource重建时id会变化的特性,给archive_file添加一个依赖参数,迫使它仅在null_resource重建时重新执行。
修改后的Terraform代码:
resource "null_resource" "lambda_buildstep" { triggers = { handler = base64sha256(file("lambda_function/lambda_function.py")) requirements = base64sha256(file("lambda_function/requirements.txt")) script = base64sha256(file("scripts/create_pkg.sh")) } provisioner "local-exec" { command = "bash ${path.module}/scripts/create_pkg.sh" environment = { source_code_path = var.path_source_code function_name = var.function_name path_module = path.module runtime = var.runtime path_cwd = path.cwd dir_name = var.distribution_pkg_folder } } } data "archive_file" "create_dist_pkg" { depends_on = [null_resource.lambda_buildstep] source_dir = "${path.cwd}/${var.distribution_pkg_folder}/" output_path = var.output_path type = "zip" # 当null_resource重建时id变化,触发archive_file重新生成 source_content = null_resource.lambda_buildstep.id source_content_filename = ".terraform_trigger" # 指定占位文件名,避免随机命名 }
说明:此方案会在压缩包中新增一个.terraform_trigger文件,若不需要可在create_pkg.sh末尾添加删除命令,或优先选择方案一。
内容的提问来源于stack exchange,提问作者kumar
相关产品推荐
相关产品推荐

