terraform {
  required_providers {
    azurerm = {
      source  = "hashicorp/azurerm"
      version = "~>3.0"
    }
  }
  backend "azurerm" {}
}
provider "azurerm" {
  subscription_id = var.subscription_id
  features {
    resource_group {
      prevent_deletion_if_contains_resources = false
    }
  }
}
data "azurerm_subscription" "primary" {}

variable "env" {
  type = string
}
variable "location" {
  type = string
}
variable "aks_oidc_issuer" {
  type = string
}
variable "subscription_id" {
  type = string
}

module "external-secrets-operator" {
  source = "../../modules/controlplane"

  location        = var.location
  aks_oidc_issuer = var.aks_oidc_issuer
  # azure-workload-identity does not support wildcard https://github.com/Azure/azure-workload-identity/issues/373
  # namespace and service_account should be exact match
  namespace           = "external-secrets"
  service_account     = "external-secrets-operator"
  identity_name       = "external-secrets-operator"
  resource_group_name = "${var.env}-${var.location}-controlplane"
}

resource "azurerm_role_assignment" "role_assignment" {
  scope                = data.azurerm_subscription.primary.id
  role_definition_name = "Key Vault Secrets User"
  principal_id         = module.external-secrets-operator.principal_id
}

output "principal_id" {
  value = module.external-secrets-operator.principal_id
}
output "client_id" {
  value = module.external-secrets-operator.client_id
}
