# https://azure.github.io/azure-workload-identity/docs/topics/service-account-labels-and-annotations.html
# https://learn.microsoft.com/en-us/azure/aks/workload-identity-deploy-cluster

# 1. configure `--enable-oidc-issuer --enable-workload-identity` on AKS
# 2. AKS will deploy a `azure-wi-webhook-controller-manager-6f6998db74-7bkbn`

# apiVersion: v1
# kind: ServiceAccount
# metadata:
#   annotations:
#     azure.workload.identity/client-id: <managed-identity-client-id>
#   name: "azcli"
# ---
# apiVersion: v1
# kind: Pod
# metadata:
#   name: sample-workload-identity
#   labels:
#     azure.workload.identity/use: "true"  # Required. Only pods with this label can use workload identity.
# spec:
#   serviceAccountName: azcli
#   containers:
#     - image: <image>
#       name: <containerName>

# similar to aws roles
resource "azurerm_user_assigned_identity" "blobcontributor" {
  name                = "dataplane-nightly-1-eastus-blob-contributor"
  resource_group_name = azurerm_resource_group.rg.name
  location            = azurerm_resource_group.rg.location
}

# similar to aws policies
resource "azurerm_role_assignment" "storage_role_assignment" {
  principal_id         = azurerm_user_assigned_identity.blobcontributor.principal_id
  role_definition_name = "Storage Blob Data Contributor"
  scope                = azurerm_storage_account.storage_account.id
}

# similar to aws trust relationship and gcp workload federation configuration for roles
resource "azurerm_federated_identity_credential" "sa_federated_credential" {
  name                = "dataplane-nightly-1-eastus-sa-federated"
  parent_id           = azurerm_user_assigned_identity.blobcontributor.id
  resource_group_name = azurerm_resource_group.rg.name
  issuer              = azurerm_kubernetes_cluster.k8s.oidc_issuer_url
  # service account in the k8s cluster
  subject             = "system:serviceaccount:default:azcli"
  audience            = ["api://AzureADTokenExchange"]
}
