provider "aws" {
  region  = var.aws_region
  profile = "gdb-crm-prod"
}

terraform {
  backend "s3" {
    bucket  = "prod-crm-terraform-state"
    key     = "dev/integration-tests/terraform.tfstate"
    region  = "us-east-1"
    encrypt = "true"
  }
}

# Full auth0 config for SMF fan API
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",
      ]
    }
  }
}

# Policy data source
data "aws_iam_policy" "secrets_policy" {
  name = "${var.environment}-ecommerce-secrets-services-ro"
}

# Jenkins agents will assume this role in order to access SecretManager
resource "aws_iam_role" "jenkins_invoke_role" {
  name               = "${var.environment}-ecommerce-integration-tests-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" "secret_manager_policy_attachment" {
  role       = aws_iam_role.jenkins_invoke_role.id
  policy_arn = data.aws_iam_policy.secrets_policy.arn
}

# SES policy
data "aws_iam_policy" "ses_policy" {
  name = "${var.environment}-ecommerce-ses_sender_policy"
}

# Attach SES policy access policy to Jenkins role.
resource "aws_iam_role_policy_attachment" "ses_policy_attachment" {
  role       = aws_iam_role.jenkins_invoke_role.id
  policy_arn = data.aws_iam_policy.ses_policy.arn
}
