locals {
  ecs_service_name = "networking-${var.environment}-ioc-block-list"
}

module "lambda_ioc_fargate_redeploy" {
  source = "git@github.com:theorchard/terraform-lambda.git//?ref=5.3.0"

  environment                    = var.environment
  lambda_name                    = "lambda-${var.service_name}-fargate-redeploy"
  application_family             = var.application_family
  lambda_description             = "Force-restarts given ECS service."
  use_container_image            = true
  datadog_advanced_enabled       = true
  vpc_id                         = module.vpc_info.vpc_id
  vpc_subnet_ids                 = module.vpc_info.default_private_subnet_ids
  lambda_function_timeout        = 900
  splitio_enabled                = false
  ows_machine_to_machine_enabled = false

  lambda_function_environment_variables = {
    Environment              = var.environment
    SERVICE_NAME             = "lambda-${var.service_name}-fargate-redeploy"
    DEFAULT_ECS_SERVICE_NAME = local.ecs_service_name
  }
}

data "aws_iam_policy_document" "fargate_redeploy_ecs_policy" {
  statement {
    effect = "Allow"
    actions = [
      "ecs:DescribeServices",
      "ecs:UpdateService",
    ]
    resources = [
      "arn:aws:ecs:${var.aws_region}:${data.aws_caller_identity.current.account_id}:service/${local.ecs_service_name}/${local.ecs_service_name}"
    ]
  }
}

resource "aws_iam_role_policy" "fargate_redeploy_ecs_policy" {
  role   = module.lambda_ioc_fargate_redeploy.lambda_role_id
  policy = data.aws_iam_policy_document.fargate_redeploy_ecs_policy.json
  name   = "ECS-lambda-${var.service_name}-fargate-redeploy-policy"
}
