0

我已按照此处的说明进行操作https://registry.terraform.io/providers/hashicorp/azurerm/latest/docs/guides/service_principal_client_secret

所以,我创建了一个服务主体

az ad sp create-for-rbac -n TerraformSP --role="Contributor" --scopes="/subscriptions/SUBSCRIPTION_ID"

这是(恢复的)terraform 脚本

resource "azurerm_resource_group" "default" {
  name     = "myaks-rg"
  location = var.location
}

resource "azurerm_kubernetes_cluster" "default" {
  name                = "myaks"
  location            = azurerm_resource_group.default.location
  resource_group_name = azurerm_resource_group.default.name
  dns_prefix          = var.dns_prefix

  identity {
    type = "SystemAssigned"
  }

  role_based_access_control {
    enabled = true
  }
}

data "azurerm_container_registry" "acr" {
  name                = "myregistry"
  resource_group_name = "another-rg"
}

resource "azurerm_role_assignment" "aks_acr" {
  scope                            = data.azurerm_container_registry.acr.id
  role_definition_name             = "AcrPull"
  principal_id                     = azurerm_kubernetes_cluster.default.kubelet_identity[0].object_id
  skip_service_principal_aad_check = true
}

然后我执行了 terraform (使用az ad sp create-for-rbac命令生成的 ID/秘密)

az logout

export ARM_CLIENT_ID="00000000-0000-0000-0000-000000000000"
export ARM_CLIENT_SECRET="00000000-0000-0000-0000-000000000000"
export ARM_SUBSCRIPTION_ID="00000000-0000-0000-0000-000000000000"
export ARM_TENANT_ID="00000000-0000-0000-0000-000000000000"
terraform apply

AKS 已创建,但 Pod 无法拉取映像。这是 pod 中的错误消息。

Failed to pull image "myregistry.azurecr.io/myimage:latest": rpc error: code = Unknown desc = Error response from daemon: Get https://myregistry.azurecr.io/v2/myimage/manifests/latest: unauthorized: authentication required...

但是,当我terraform apply使用我的个人帐户 ( az login) 运行并且我没有设置环境变量 ARM_CLIENT_ID、ARM_CLIENT_SECRET 等时,它可以工作......

我了解服务主体 TerraformSP(角色贡献者)无法将角色分配AcrPullazurerm_kubernetes_cluster.default.kubelet_identity[0].object_id.

在这种情况下,最佳做法是什么?我应该为 TerraformSP 分配一些管理员角色吗?或者,我是否遗漏了 terraform 脚本中的某些内容?

目标是将此 terraform 脚本放入 Azure DevOps 的管道中。

4

1 回答 1

1

通过重新创建具有角色的服务主体,我设法让 Kubernetes 从我的注册表中提取图像Owner

az ad sp create-for-rbac -n TerraformSP --role="Owner" --scopes="/subscriptions/SUBSCRIPTION_ID"

我还注意到 terraform 成功创建了角色分配。

azurerm_role_assignment.aks_acr: Creation complete after 24s [id=/subscriptions/SUBSCRIPTION_ID/resourceGroups/another-rg/providers/Microsoft.ContainerRegistry/registries/myregistry/providers/Microsoft.Authorization/roleAssignments/SOME_ID]
于 2020-12-03T15:24:08.183 回答