provider "aws" {
  region = var.aws_region
}

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

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

  environment                    = var.environment
  service_name                   = var.service_name
  secret_name                    = each.value
  application_family             = var.application_family
  secret_recovery_window_in_days = 7
}

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

    actions = [
      "secretsmanager:GetSecretValue",
    ]

    resources = concat(
      [for s in values(module.secrets) : s.secret_arn],
      [for s in values(module.m2m_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",
      ]
    }
  }
}

# SecretManager Access Policy
resource "aws_iam_policy" "deploy_policy" {
  name   = "${var.environment}-${var.service_name}-deploy-policy"
  policy = data.aws_iam_policy_document.build_policy_document.json
}

# Jenkins pipeline agents will assume this role in order to access SecretManager
resource "aws_iam_role" "deploy_role" {
  name               = "${var.environment}-${var.service_name}-deploy-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" "policy_attachment" {
  role       = aws_iam_role.deploy_role.id
  policy_arn = aws_iam_policy.deploy_policy.arn
}
