如何在 Terraform 的子模块中使用 locals

huangapple go评论61阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2023年2月18日 18:13:02
  • 转载请务必保留本文链接:https://go.coder-hub.com/75492609.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定