module "default_tags" {
  source             = "git@github.com:theorchard/terraform-default-tags.git//?ref=2.0.0"
  environment        = var.environment
  application_family = var.application_family
  team_name          = var.team_name
}

provider "aws" {
  region = var.aws_region

  default_tags {
    tags = module.default_tags.tags
  }
}

terraform {
  backend "s3" {
    bucket  = "qa-songwhip-terraform-state"
    key     = "qa/iam/roles/jenkins-pipeline-deploy-role/terraform.tfstate"
    region  = "us-east-1"
    encrypt = "true"
  }
}

data "aws_caller_identity" "current" {}

# Jenkins pipeline deploy role
resource "aws_iam_role" "jenkins_pipeline_deploy_role" {
  name               = "${var.environment}-songwhip-jenkins-pipeline-deploy-role"
  assume_role_policy = data.aws_iam_policy_document.jenkins_assume_role_policy.json
}

# Trust policy allowing Jenkins from prod account to assume this role
data "aws_iam_policy_document" "jenkins_assume_role_policy" {
  statement {
    actions = ["sts:AssumeRole"]
    principals {
      type = "AWS"
      identifiers = [
        "arn:aws:iam::437795906767:role/prod-jenkins-aws-pipeline-agent",
      ]
    }
  }
}

# SecretsManager read access for specific secrets
data "aws_iam_policy_document" "secrets_read" {
  statement {
    effect = "Allow"

    actions = [
      "secretsmanager:GetSecretValue",
      "secretsmanager:DescribeSecret",
    ]

    resources = [
      for secret in var.secrets_to_access :
      "arn:aws:secretsmanager:${var.aws_region}:${data.aws_caller_identity.current.account_id}:secret:${secret}*"
    ]
  }
}

resource "aws_iam_policy" "secrets_read" {
  name   = "${var.environment}-songwhip-jenkins-pipeline-deploy-secrets-read"
  policy = data.aws_iam_policy_document.secrets_read.json
}

resource "aws_iam_role_policy_attachment" "secrets_read" {
  role       = aws_iam_role.jenkins_pipeline_deploy_role.name
  policy_arn = aws_iam_policy.secrets_read.arn
}
