如何在Terraform子模块中使用根模块的locals变量
Terraform子模块引用根模块本地变量的正确方式
问题场景
在Terraform根模块的local.tf中定义了本地变量:
locals { customer_env = "${var.customer_name}-${var.env}" }
但在子模块modules/ecs/ecs.tf中直接引用local.customer_env时,触发报错:
Error: Reference to undeclared local value │ │ on modules/ecs/ecs.tf line 2, in resource "aws_ecs_cluster" "main": │ 2: name = "${local.customer_env}" │ │ A local value with the name "customer_env" has not been declared. ╵
原因是Terraform本地变量的作用域仅限于定义它的模块,子模块无法直接访问根模块的本地变量,必须通过变量传递的方式实现。
解决步骤
1. 在子模块中声明接收变量
在modules/ecs/variable.tf中添加需要接收的变量定义,明确变量类型和描述:
variable "customer_env" { description = "组合后的客户名称与环境标识" type = string }
2. 根模块调用子模块时传递变量
在根模块的main.tf中调用ecs模块时,将根模块的local.customer_env作为参数传递给子模块:
module "ecs" { source = "./modules/ecs" customer_env = local.customer_env env = var.env # 保留原有需要传递的变量 }
3. 子模块中引用传入的变量
修改modules/ecs/ecs.tf中的资源定义,将原有的local.customer_env替换为传入的模块变量:
resource "aws_ecs_cluster" "main" { name = var.customer_env tags = { Environment = var.env } }
完成以上修改后,子模块即可正确获取根模块生成的customer_env值。
内容的提问来源于stack exchange,提问作者Vamsi
相关产品推荐
相关产品推荐

