provider "aws" {
  region = var.aws_region
}

# Terraform backends cannot contain interpolations
terraform {
  backend "s3" {
    bucket  = "orcd-terraform-state"
    key     = "prod/cloudsearch/dev-etl-releases/terraform.tfstate"
    region  = "us-east-1"
    encrypt = "true"
  }
}

data "aws_caller_identity" "current" {}

data "aws_iam_policy_document" "access_policy" {
  statement {
    effect = "Allow"

    principals {
      type        = "AWS"
      identifiers = ["*"]
    }

    actions = [
      "cloudsearch:search",
    ]

    condition {
      test     = "IpAddress"
      variable = "aws:SourceIp"
      values   = [
        "207.237.185.1/26",
        "54.173.186.206/32",
        "52.202.238.54/32",
        "10.100.0.0/16",
        "10.70.0.0/22",
        "208.91.130.128/25",
        "10.30.0.0/22",
        "3.213.73.88/32",
        "3.81.188.77/32",
        "34.196.231.107/32",
        "34.198.230.207/32",
        "71.105.133.184/32",
        "34.200.140.205/32", # shared account NAT gateway
        "100.25.234.141/32", # shared account NAT gateway
        "54.160.83.19/32",   # shared account NAT gateway
      ]
    }
  }
}

resource "aws_cloudsearch_domain_service_access_policy" "access_policy" {
  domain_name   = "${var.environment}-${var.service_name}"
  access_policy = data.aws_iam_policy_document.access_policy.json
}
