Terraform同for_each循环引用父资源报Cycle循环依赖错误如何解决?
错误原因
你遇到的循环报错是因为Terraform在解析同个aws_api_gateway_resource.res资源块下的多个实例依赖时,原有写法触发了依赖链路的误判,同时你写的depends_on规则不符合规范(depends_on只能指定完整资源对象,不能指定资源的单个属性)。
修复方案
步骤1:简化变量定义
去掉不需要的parent布尔字段,统一用parent_resource标记父级资源,根层级的资源直接标记父级为root即可:
# vars.tf variable "resources" { type = map(object({ parent_resource = string })) default = { "test" = { parent_resource = "root" }, "testchild" = { parent_resource = "test" } } }
步骤2:修正资源块逻辑
直接复用AWS API Gateway默认生成的根路径资源IDaws_api_gateway_rest_api.demo.root_resource_id作为根层级资源的父ID,删掉冗余的depends_on配置(你已经引用了rest_api_id,隐式依赖已经生效):
# ag.tf resource "aws_api_gateway_rest_api" "demo" { name = "demo-api" description = "This is demo" endpoint_configuration { types = ["REGIONAL"] } } resource "aws_api_gateway_resource" "res" { for_each = var.resources rest_api_id = aws_api_gateway_rest_api.demo.id parent_id = each.value.parent_resource == "root" ? aws_api_gateway_rest_api.demo.root_resource_id : aws_api_gateway_resource.res[each.value.parent_resource].id path_part = each.key }
步骤3:验证配置
执行terraform plan即可看到Terraform会先创建test资源,再创建testchild资源,不会再触发循环报错。
拓展建议
如果需要后续给资源绑定HTTP方法,你可以在变量里增加methods列表字段,再新增对应的aws_api_gateway_method资源块用for_each批量创建即可。
内容的提问来源于stack exchange,提问作者tarkikshah
相关产品推荐
相关产品推荐

