provider "aws" {
  region = var.aws_region
}

terraform {
  backend "s3" {
    bucket  = "orcd-terraform-state"
    key     = "qa/iam/jenkins/terraform.tfstate"
    region  = "us-east-1"
    encrypt = "true"
  }
}

data "aws_caller_identity" "current" {}

data "aws_iam_policy_document" "db_refresh_pipeline_policy_document" {
  statement {
    actions = [
      "ecs:ListServices",
      "ecs:DescribeServices"
    ]
    resources = ["*"]
  }
  statement {
    actions = [
      "ecs:UpdateService"
    ]
    resources = [
      "arn:aws:ecs:*:${data.aws_caller_identity.current.account_id}:service/${var.environment}-kafka-connect-*"
    ]
  }
}

data "aws_iam_policy_document" "assume_role_policy" {
  statement {
    actions = ["sts:AssumeRole"]

    principals {
      type = "AWS"

      identifiers = [
        "arn:aws:iam::${data.aws_caller_identity.current.account_id}:role/prod-jenkins-aws-pipeline-agent",
      ]
    }
  }
}

resource "aws_iam_role" "db_refresh_pipeline_role" {
  name          = "${var.environment}-db-refresh-pipeline"
  force_detach_policies = true
  assume_role_policy = data.aws_iam_policy_document.assume_role_policy.json
  tags = {
    environment = var.environment
    terraformed = "true"
  }
}

resource "aws_iam_policy" "db_refresh_pipeline_policy" {
  name   = "${var.environment}-db-refresh-pipeline-policy"
  policy = data.aws_iam_policy_document.db_refresh_pipeline_policy_document.json

  tags = {
    environment = var.environment
    terraformed = "true"
  }
}

resource "aws_iam_role_policy_attachment" "db_refresh_pipeline_policy_attachment" {
  role       = aws_iam_role.db_refresh_pipeline_role.name
  policy_arn = aws_iam_policy.db_refresh_pipeline_policy.arn
}
