provider "aws" {
  region = var.aws_region
}

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

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

  environment                    = var.environment
  service_name                   = var.service_name
  secret_name                    = each.value
  application_family             = var.application_family
  secret_recovery_window_in_days = 30

  additional_tags = {
    secret_type = "integration-tests"
  }
}

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

    actions = [
      "secretsmanager:GetSecretValue",
    ]

    resources = [for s in values(module.integration_test_secrets) : s.secret_arn]
  }
}


# Assume role policy used by Jenkins pipeline agent role
data "aws_iam_policy_document" "assume_role_policy" {
  statement {
    actions = ["sts:AssumeRole"]

    principals {
      type = "AWS"

      identifiers = [
        "arn:aws:iam::437795906767:role/prod-jenkins-aws-pipeline-agent",
        "arn:aws:iam::591204808501:role/permissions-platform-role",
        "arn:aws:iam::103233932089:role/generic-engineer-role",
      ]
    }
  }
}



# SecretManager Access Policy
resource "aws_iam_policy" "secrets_manager_policy" {
  name   = "SecretManager-ows-features-int-refresh-access-policy"
  policy = data.aws_iam_policy_document.secrets_manager_policy_document.json
}

# Jenkins pipeline agents will assume this role in order to access SecretManager
resource "aws_iam_role" "jenkins_invoke_role" {
  name               = "${var.environment}-ows-features-integration-test-role"
  assume_role_policy = data.aws_iam_policy_document.assume_role_policy.json
}

# Attach SecretManager access policy to Jenkins role.
resource "aws_iam_role_policy_attachment" "ows_features_integration_secret_manager_policy_attachment" {
  role       = aws_iam_role.jenkins_invoke_role.id
  policy_arn = aws_iam_policy.secrets_manager_policy.arn
}
