需要 Terraform 模块参数 VAR,但未找到定义

Terraform modules argument VAR is required, but no definition was found

我有 Terraform 模块来配置 AWS 资源。在 terraform plan 之后,我看到以下错误:

错误:缺少必需的参数 main.tf 第 113 行,在模块“ecs-task-execution-role”中: 113:模块“ecs-task-execution-role”{ 需要参数“iam_role_name”,但未找到定义。

这是我在 ../terraform/modules/iam/ecs_iam.tf 中定义的资源:

resource "aws_iam_role" "iam--task-execution-role" {
  name               = var.iam_role_name
  assume_role_policy = data.aws_iam_policy_document.ecs-task-assume-role.json
}

data "aws_iam_policy_document" "ecs-task-assume-role" {
  statement {
    actions = ["sts:AssumeRole"]

    principals {
      type        = "Service"
      identifiers = ["ecs-tasks.amazonaws.com"]
    }
  }
}

data "aws_iam_policy" "ecs-task-execution-role" {
  arn = "arn:aws:iam::aws:policy/service-role/AmazonECSTaskExecutionRolePolicy"
}

# Attach the above policy to the execution role.

resource "aws_iam_role_policy_attachment" "ecs-task-execution-role" {
  role       = aws_iam_role.iam-task-execution-role.name
  policy_arn = data.aws_iam_policy.ecs-task-execution-role.arn
}

变量定义在../terraform/modules/iam/variables.tf:

variable "iam_role_name" {
  type = string
}

模块在../terraform/production/main.tf:

module "iam-jo-task-execution-role" {

  source = "../modules/iam"

  iam_role_name = "iam-jo-task-execution-role"

}

# Attach the above policy to the execution role.

module "ecs-task-execution-role" {

  source = "../modules/iam"

}

感谢任何帮助。

在你的例子中:

module "iam-jo-task-execution-role" {

  source = "../modules/iam"

  iam_role_name = "iam-jo-task-execution-role"

}

# Attach the above policy to the execution role.

module "ecs-task-execution-role" {

  source = "../modules/iam"

}

您没有将 iam_role_name 变量的值传递给 ecs-task-execution-role 模块。它正上方的 iam-jo-task-execution-role 模块显示了如何将变量传递给模块。

原来是我误解了 Terraform 中的资源和模块。

在声明使用源 ../modules/iam 中的资源的 ../terraform/production/main.tf 文件中,我需要以下语法:

module "iam-jo-task-execution-role" {

  source = "../modules/iam"

  iam_role_name = "iam-jo-task-execution-role"

}

无需为 ../terraform/modules/iam/ecs_iam.tf 中声明的每个资源定义模块。这只是几个资源的分组(打包)。