1

currently I'm writing a Terraform to create an AWS Elastic Container Service and I am struggeling a bit with the container_definitions. So this is my code:

resource "aws_ecs_task_definition" "task" {
  family                   = "${var.cluster_name}-task"
  cpu                      = var.task_cpu
  memory                   = var.task_memory
  network_mode             = "awsvpc"
  requires_compatibilities = ["FARGATE"]
  execution_role_arn       = aws_iam_role.ecs_task_execution_role.arn
  task_role_arn            = aws_iam_role.ecs_task_role.arn
  container_definitions = jsonencode([{
    name      = "${var.cluster_name}-container"
    image     = var.container_image
    cpu       = var.task_cpu
    memory    = var.task_memory
    essential = true
    portMappings = [
      {
        name          = "${var.cluster_name}-${var.container_port}-to-${var.host_port}"
        containerPort = var.container_port
        hostPort      = var.host_port
      }
    ],
    environment = var.task_environment,
    // HERE I NEED HELP

    // END
    logConfiguration : {
      logDriver : "awslogs",
      options : {
        "awslogs-group" : "${var.cluster_name}-log-group"
        "awslogs-region" : data.aws_region.current.name,
        "awslogs-stream-prefix" : "esc"
      }
    }
  }])
}

I need to add this part in the code above

healthCheck = {
  command : var.healthcheck_cmd
  interval : 30,
  retries : 3,
  timeout : 5
}

My problem is - Sometimes I need and sometimes I don't need a Healthcheck, so this part needs to be flexible. If Healthcheck is set, I want to add it otherwise not.

How to solve this one in Terraform ?

Tested with count, dynamic block etc.

Mark B
  • 183,023
  • 24
  • 297
  • 295
tsluga
  • 11
  • 1
  • You forgot to explain what's wrong with the current code? Any errors? – Marcin Aug 20 '23 at 06:18
  • Check conditional logic using the ternary conditional expression in Terraform. You can check if the healthcheck_cmd variable is set (or any other condition) and then decide whether to include the healthCheck block or not. – Piyush Patil Aug 20 '23 at 16:20

1 Answers1

0

I would try setting a local variable to the healthcheck value, or an empty map:

locals {
  healthcheck = var.healthcheck_cmd != null ? {
    command : var.healthcheck_cmd
    interval : 30,
    retries : 3,
    timeout : 5
  } : {}
}

Then in the container definition:

environment = var.task_environment,
healthCheck = local.healthcheck

I haven't tested passing an empty map {} for an ECS health check. If that gives you an error you might try passing null instead of {}.

Mark B
  • 183,023
  • 24
  • 297
  • 295