provider "aws" {
  region = var.aws_region
}

# Terraform backends cannot contain interpolations
terraform {
  backend "s3" {
    bucket  = "dev-orcd-terraform-state"
    key     = "dev/kafka-infra/ksqldb-server/terraform.tfstate"
    region  = "us-east-1"
    encrypt = "true"
  }
}

data "aws_caller_identity" "current" {}

module "ksqldb_server_fargate_environment" {
  source = "git@github.com:theorchard/terraform-fargate.git//?ref=3.8.0"

  environment                       = var.environment
  service_name                      = var.service_name
  aws_region                        = var.aws_region
  application_family                = var.application_family
  use_custom_task_definition_file   = true
  task_definition_file_location     = file("ksqldb-server.json")
  service_platform_version          = "1.4.0"
  desired_task_count                = 1
  minimum_capacity                  = 1
  maximum_capacity                  = 1
  task_cpu                          = 4096
  task_memory                       = 8192
  container_port                    = 8000
  container_protocol_version        = "HTTP1"
  health_check_grace_period_seconds = 300
  web_service_health_check_command  = "/usr/bin/bash /usr/local/bin/healthcheck.sh"
  health_check_path                 = "/healthcheck"
  vpc_id                            = "vpc-34dbfd51"
}

# This rule will allow kafka-connect tasks to communicate with each other in distributed mode
resource "aws_security_group_rule" "allow_intra_cluster_communication" {
  from_port         = 8088
  to_port           = 8088
  protocol          = "tcp"
  security_group_id = module.ksqldb_server_fargate_environment.fargate_security_group_id
  self              = true
  type              = "ingress"
}

module "ksqldb_server_secrets" {
  source   = "git@github.com:theorchard/terraform-secrets-manager.git//?ref=1.0.6"
  for_each = toset(var.secrets_manager_secret_names)

  application_family = var.application_family
  environment        = var.environment
  service_name       = var.service_name
  secret_name        = each.value
}
