resource "aws_alb_target_group" "main" {
  name         = "${var.env}-${var.serviceName}"
  port         = "${var.containerPort}"
  protocol     = "HTTP"
  vpc_id       = "${data.terraform_remote_state.network.VPCId}"
  health_check = [ "${var.healthcheck}" ]
  target_type = "ip"
}


variable "ALB_HOST_HEADER" {
 type = "string"
}


variable "ALB_HOST_HEADER_MER" {
 type = "string"
}

variable "healthcheck" {
  default = {
    healthy_threshold   = 2
    unhealthy_threshold = 5
    timeout             = 5
    path                = "/"
    interval            = 30
    matcher             = "200-305"
  }
}

resource "aws_alb_listener_rule" "main" {
  listener_arn = "${data.terraform_remote_state.app-tier.listenerARN}"

  action {
    type             = "forward"
    target_group_arn = "${aws_alb_target_group.main.arn}"
  }

  condition {
    field  = "host-header"
    values = ["${var.ALB_HOST_HEADER}"]
  }
  lifecycle {
    ignore_changes = ["priority"]
  }
}

resource "aws_alb_listener_rule" "mer" {
  listener_arn = "${data.terraform_remote_state.app-tier.listenerARN}"

  action {
    type             = "forward"
    target_group_arn = "${aws_alb_target_group.main.arn}"
  }

  condition {
    field  = "host-header"
    values = ["${var.ALB_HOST_HEADER_MER}"]
  }
  lifecycle {
    ignore_changes = ["priority"]
  }
}
