Search code examples
amazon-web-servicesterraformamazon-ecsterraform-provider-aws

How to make an attribute block within a terraform resource conditional?


I have a terraform module for creating an ECS service and task definition, along with some other related resources. This is used for a few different services with slightly different requirements.

The issue I'm running into is that only one of my services has a task needing a mounted volume. I'm trying to write a condition so that the volume will only be created in the task definition for that particular service - something like

resource "aws_ecs_task_definition" "task_definition" {
  family                   = var.service_task_name
  requires_compatibilities = ["FARGATE"]
  network_mode             = "awsvpc"
  cpu                      = var.cpu
  memory                   = var.memory
  execution_role_arn       = aws_iam_role.execution.arn
  task_role_arn            = aws_iam_role.task.arn

  count = var.volume_name != null ? 1 : 0
    volume {
      name = var.volume_name

      efs_volume_configuration {
        file_system_id          = var.efs_id
        root_directory          = "/"
        transit_encryption      = "ENABLED"
        transit_encryption_port = 2999
        authorization_config {
          access_point_id = var.efs_access_point_id
          iam             = "ENABLED"
        }
      }
    }

  container_definitions = jsonencode([
...

The variable volume_name is only set for that task and is set to null elsewhere, along with efs_id and efs_access_point_id. Essentially what I need is "if var.volume_name = null, skip the volume block". Obviously this code doesn't work but I hope it shows what I'm trying to achieve.

I've tried to use dynamic blocks too but using for_each doesn't work here as they're all separate resources and not a list I can iterate over - unless I'm misunderstanding the use of dynamic blocks.


Solution

  • I think this should work with dynamic block:

    resource "aws_ecs_task_definition" "task_definition" {
      family                   = var.service_task_name
      requires_compatibilities = ["FARGATE"]
      network_mode             = "awsvpc"
      cpu                      = var.cpu
      memory                   = var.memory
      execution_role_arn       = aws_iam_role.execution.arn
      task_role_arn            = aws_iam_role.task.arn
    
      dynamic "volume" {
        for_each = var.volume_name != null ? [1] : []
        content {
          name = var.volume_name
          efs_volume_configuration {
            file_system_id          = var.efs_id
            root_directory          = "/"
            transit_encryption      = "ENABLED"
            transit_encryption_port = 2999
            authorization_config {
              access_point_id = var.efs_access_point_id
              iam             = "ENABLED"
            }
          }
        }
      }
    
      container_definitions = jsonencode([
    ...