Terraform Azure 如何获取 AKS 服务主体对象 ID

Terraform Azure how to get AKS service principle object id

我正在尝试使用 Terraform 创建 AKS、ACR 和 role_assignment 到 AKS 的服务主体。在这里我想利用用 AKS 创建的 SP。

我指的是 AKS Create cluster 它说在创建 aks 集群时会用它创建一个 SP。

 provider "azurerm" {
  version         = "~> 1.31.0"
  client_id       = ""
  client_secret   = ""
  tenant_id       = ""
  subscription_id = ""

}

variable "tftranining_rg_name" {}

variable "tftranining_rg_location" {}

resource "azurerm_resource_group" "terraform_training_rg" {
  name     = "${var.tftranining_rg_name}"
  location = "${var.tftranining_rg_location}"
}

resource "azurerm_kubernetes_cluster" "k8s_gateway" {
  resource_group_name = "${var.tftranining_rg_name}"
  name                = "terraform_training_aks"
  location            = "${var.tftranining_rg_location}"
  dns_prefix          = "terraform_training_aks_dns"

  agent_pool_profile {
    name            = "agentpool"
    count           = "1"
    vm_size         = "Standard_DS1_v2"
    os_type         = "Linux"
    os_disk_size_gb = 10
  }
}

resource "azurerm_container_registry" "terraform_training_acr" {
  # registry name can only contain alpha numeric characters
  name                = "terraformtrainingacr"
  location            = "${var.tftranining_rg_location}"
  resource_group_name = "${var.tftranining_rg_name}"
  sku                 = "Basic"
  admin_enabled       = true
}

#We need to give AKS's Service principal "Contributor" role for accessing ACR
resource "azurerm_role_assignment" "aks_acr_pullimage" {
  #scope on which we are to assign this role
  scope = "${azurerm_container_registry.lterraform_training_acr.id}"
  #this refers to a builtin role definition
  role_definition_name = "AcrPull"
  #passing AKS's service principal's object id
  principal_id = "AKS SP Object ID"
}

是否可以在角色分配中引用 AKS 服务主体的对象 ID 而无需将其作为变量传递。

我希望使用通过 AKS 创建的默认 SP。

这可以使用命令来完成。我们可以使用 terraform 做同样的事情吗? Get SP using az cli

正在查看 resource documented exports 客户端 ID 未被导出。所以你无能为力(鉴于缺乏 AKS 的数据资源)。

您可以使用脚本资源动态检索客户端 ID(例如,使用 azure cli)。

创建 AKS 群集时,服务主体是必需的。在 Terraform 中,它也是必需的参数。而且AKS集群也没有暴露Terraform中的principal Id,所以不能通过其中的AKS资源引用AKS principal Id。

据我所知,有两种方法可以使用服务主体而不将其作为变量传递。

一种方法是创建 service principal with the password。然后就可以引用它在AKS集群中的服务主体Id和密码以及角色分配了。

另一种方法是使用Terraform external data resource with running a script that contains the Azure CLI command to create a service principal。然后你也可以根据需要引用服务主体Id和密码。