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

6.9k views Asked by At

I have Terraform modules to provision AWS resources. After terraform plan, I see the following error:

Error: Missing required argument on main.tf line 113, in module "ecs-task-execution-role": 113: module "ecs-task-execution-role" { The argument "iam_role_name" is required, but no definition was found.

Here is my resource defined in ../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
}

Variables are defined in ../terraform/modules/iam/variables.tf:

variable "iam_role_name" {
  type = string
}

The module is in ../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"

}

Any help appreciated.

2

There are 2 answers

0
Confounder On BEST ANSWER

It turns out I misunderstood resources and modules in Terraform.

In the ../terraform/production/main.tf file that declares the use of resources found in the source ../modules/iam, I needed the following syntax:

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

  source = "../modules/iam"

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

}

There is no need to define a module for each resource declared in ../terraform/modules/iam/ecs_iam.tf. This is just a grouping (packaging) of several resources.

0
Montgomery Watts On

In your example:

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"

}

You are not passing a value for the iam_role_name variable to the ecs-task-execution-role module. The iam-jo-task-execution-role module right above it shows how to pass a variable to the module.