davidb
davidb

Reputation: 1603

Terraform dynamic block

I'm having trouble creating a dynamic block in Terraform. I'm trying to create an ECS service using a module. In the module I want to specify that network_configuration block should be created only if a variable is present. Here's my module code:

resource "aws_ecs_service" "service" {


name = var.name
  cluster = var.cluster
  task_definition = var.task_definition
  desired_count = var.desired_count
  launch_type = var.launch_type
  load_balancer {
    target_group_arn = var.lb_target_group
    container_name   = var.container_name
    container_port   = var.container_port
  }

  dynamic "network_configuration" {
    for_each = var.network_config
    content {
      subnets = network_configuration.value["subnets"]
      security_groups = network_configuration.value["security_groups"]
      assign_public_ip = network_configuration.value["public_ip"]
    }
  }
}

Next is code for the actual service:

module "fargate_service" {
  source = "./modules/ecs/service"
  name = "fargate-service"
  cluster = module.ecs_cluster.id
  task_definition = module.fargate_task_definition.arn
  desired_count = 2
  launch_type = "FARGATE"
  lb_target_group = module.target_group.arn
  container_name = "fargate_definition"
  container_port = 8000
  network_config = local.fargate_network_config
}

Finally my locals file looks like this:

locals {
    fargate_network_config = {
      subnets          = module.ec2_vpc.private_subnet_ids
      public_ip        = "false"
      security_groups  = [module.fargate_sg.id]
  }
}

With the above configuration I wish to create one network_configiration block only when network_config variable is present. If I don't define it I want the module not to bother creating the block. I'm getting Invalid index error.

network_configuration.value is tuple with 3 elements
The given key does not identify an element in this collection value: a number
is required.

What is wrong with my code? This is my first time using dynamic blocks in Terraform but I want to be able to understand it. Thanks

Upvotes: 3

Views: 4872

Answers (1)

marcincuber
marcincuber

Reputation: 3791

So your locals should be as follows:

locals {
  fargate_network_config = [
    {
      subnets          = module.ec2_vpc.private_subnet_ids
      public_ip        = "false"
      security_groups  = [module.fargate_sg.id]
    }
  ]
}

Then fix your variable network_config to be a list.

Finally your dynamic block:

dynamic "network_configuration" {
  for_each = var.network_config
    content {
      subnets = lookup(network_configuration.value, "subnets", null)
      security_groups = lookup(network_configuration.value, "security_groups", null)
      assign_public_ip = lookup(network_configuration.value, "public_ip", null)
    }
}

hope that helps

Upvotes: 3

Related Questions