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  = "prod-songwhip-terraform-state"
    key     = "prod/iam/roles/jenkins-pipeline-deploy-role/terraform.tfstate"
    region  = "us-east-1"
    encrypt = "true"
  }
}

data "aws_caller_identity" "current" {}

# Jenkins pipeline deploy role
# The role is created in terraform-infra-core/songwhip-prod/iam/generic_resources/jenkins_policies.tf
data "aws_iam_role" "jenkins_pipeline_deploy_role" {
  name = "${var.environment}-songwhip-jenkins-pipeline-deploy-role"
}

# 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       = data.aws_iam_role.jenkins_pipeline_deploy_role.name
  policy_arn = aws_iam_policy.secrets_read.arn
}
