You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Terraform如何为动态命名模块配置data块的depends_on依赖?

解决方案

问题根源在于:Terraform的data数据源默认在计划阶段执行查询,但你的升级策略(escalation_policy)是在应用阶段才创建的,计划阶段查询时资源还未存在,因此报错。下面提供三种解决方式,按推荐程度排序:

方法1:直接引用模块输出的ID(推荐)

这种方式无需手动添加依赖,Terraform会自动处理执行顺序,且用ID查询比名称更可靠(避免名称重复风险)。

  1. 在modules/escalation_policy模块中添加输出配置:
output "escalation_policy_id" {
  value = pagerduty_escalation_policy.escalation_policy.id
}
  1. 修改你的data模块,将输入变量从名称替换为ID:
variable "escalation_policy_id" {
  type        = string
  description = "目标升级策略的ID"
}

data "pagerduty_escalation_policy" "escalation_policy" {
  id = var.escalation_policy_id
}
  1. 调用data模块时,直接传入对应升级策略模块的输出ID:
module "escalation_policy_data_1" {
  source = "./modules/你的data模块路径"
  escalation_policy_id = module.escalation_policy_1.escalation_policy_id
}

方法2:调用data模块时手动添加depends_on

如果必须通过名称查询,可以在调用data模块时,用depends_on强制指定依赖关系:

module "escalation_policy_data_1" {
  source = "./modules/你的data模块路径"
  escalation_policy_name = "Escalation Policy 1"

  # 强制先完成escalation_policy_1的创建,再执行data查询
  depends_on = [module.escalation_policy_1]
}

方法3:给data模块添加依赖变量(通用场景)

如果data模块需要被多场景调用,每个场景依赖不同资源,可以给模块添加接收依赖列表的变量,让调用方灵活传入:

  1. 在data模块的variables.tf中新增变量:
variable "depends_on_resources" {
  type        = list(any)
  description = "查询前需等待创建完成的资源列表"
  default     = []
}
  1. 在data块中绑定依赖:
data "pagerduty_escalation_policy" "escalation_policy" {
  name = var.escalation_policy_name

  depends_on = var.depends_on_resources
}
  1. 调用data模块时传入对应依赖:
module "escalation_policy_data_1" {
  source = "./modules/你的data模块路径"
  escalation_policy_name = "Escalation Policy 1"
  depends_on_resources = [module.escalation_policy_1]
}

内容的提问来源于stack exchange,提问作者Gary Turner

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.11 16:50:28