Search code examples
azureterraformterraform-provider-azure

Terraform Azure how to get AKS service principle object id


I am trying to create AKS, ACR and a role_assignment to AKS' service principal using Terraform. Here i want to utilise the SP created with AKS.

I am referring to AKS Create cluster it says while creating an aks cluster it creates a SP with it.

 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"
}

Is it possible to refer to the AKS' Service principal's object id in role assignment without passing it as variable.

I am expecting to use the default SP created with AKS.

This can be done using commands. Can we do the same using terraform. Get SP using az cli


Solution

  • When you create the AKS cluster, the service principal is necessary. In Terraform, it's also a required parameter. And the AKS cluster also does not expose the principal Id in the Terraform, so you cannot quote the AKS principal Id through the AKS resource in it.

    As I know, there are two ways to use the service principal without passing it as the variable.

    One way is to create a service principal with the password. Then you can quote its service principal Id and password in the AKS cluster and the role assignment.

    Another way is to use the Terraform external data resource with running a script that contains the Azure CLI command to create a service principal. Then you can also quote the service principal Id and password as you want.