provider "aws" {
  region = var.aws_region
}

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

terraform {
  required_providers {
    elasticsearch = {
      source  = "phillbaker/elasticsearch"
      version = "2.0.7"
    }
    aws = {
      source = "hashicorp/aws"
    }
  }
}

data "aws_caller_identity" "current" {}

# If you need to run this locally, add a principal to this trust policy
data "aws_iam_policy_document" "assume_role_policy" {
  statement {
    actions = ["sts:AssumeRole"]

    principals {
      type = "AWS"

      identifiers = [
        "AROAWL3VLMTH72X2NP5PT",
        "arn:aws:iam::${data.aws_caller_identity.current.account_id}:role/cross-account-atlantis-role",
      ]
    }
  }
}

# Role exclusively used for creating Elasticsearch indices
resource "aws_iam_role" "es_index_role" {
  name               = "${var.environment}-es-index-role"
  assume_role_policy = data.aws_iam_policy_document.assume_role_policy.json
}

provider "elasticsearch" {
  url                   = "https://vpc-prod-music-graph-qyptwfcbuw6wzjnzg5k7adqnim.us-east-1.es.amazonaws.com/"
  healthcheck           = false
  elasticsearch_version = "7.8"
  aws_assume_role_arn   = aws_iam_role.es_index_role.arn
}

#│ Error: Cycle: elasticsearch_index.global_participants (destroy), elasticsearch_index.globalparticipants (destroy), elasticsearch_index.global_sound_recordings (destroy), provider["registry.terraform.io/phillbaker/elasticsearch"], elasticsearch_index.globalsoundrecordings (destroy), aws_iam_role.es_index_role
