英文:
How to use locals in child modules in terraform
问题
local.tf
locals {
customer_env = "${var.customer_name}-${var.env}"
}
modules/ecs/ecs.tf
resource "aws_ecs_cluster" "main" {
name = "${local.customer_env}"
tags = {
Environment = var.env
}
}
Tried that way but throwing an error:
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.
英文:
I've locals.tf in root module and want to use it to child modules. Directory structure is as follows:
.
├── env.tfvars
├── local.tf
├── main.tf
├── modules
│   ├── alb
│   │   ├── alb.tf
│   │   ├── output.tf
│   │   └── variable.tf
│   ├── ecr
│   │   ├── ecr.tf
│   │   ├── output.tf
│   │   └── variable.tf
│   ├── ecs
│   │   ├── ecs.tf
│   │   └── variable.tf
local.tf
locals {
customer_env = "${var.customer_name}-${var.env}"
}
Wanted to use this locals into child modules.
modules/ecs/ecs.tf
resource "aws_ecs_cluster" "main" {
name = "${local.customer_env}"
tags = {
Environment = var.env
}
}
Tried that way but throwing an error
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.
╵
答案1
得分: 2
Child modules do not inherit variables and locals from the parent module. You have to explicitly pass them in. So, for example for your ecs
module you have to pass the local in:
module "ecs" {
source = "./modules/ecs"
customer_env = local.customer_env
}
Obviously in the ecs
module, you have to have the corresponding variable:
variable "customer_env" {}
And the aws_ecs_cluster.main
will use the variable:
resource "aws_ecs_cluster" "main" {
name = var.customer_env
tags = {
Environment = var.env
}
}
You have to do it for all your modules.
英文:
Child modules do not inherit variables and locals from the parent module. You have to explicitly pass them in. So, for example for your ecs
module you have pass the local in:
module "ecs" {
source = "./modules/ecs"
customer_env = local.customer_env
}
Obviously in the ecs
module you have to have the corresponding variable:
variable "customer_env" {}
And the aws_ecs_cluster.main
will use the variable:
resource "aws_ecs_cluster" "main" {
name = var.customer_env
tags = {
Environment = var.env
}
}
You have to do it for all your modules.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论