Terraform on gcloud: serviceaccounts is forbidden: User "system:anonymous" cannot create resource "serviceaccounts"

I am trying to write terraform code for bootstrapping a GKE cluster (with RBAC) on Google Cloud. The GKE cluster successfully created, but I want to create a service account as wel which I can reuse for my later kubernetes provider configuration. This means that I need to use the kubernetes provider in my submodule to temporarily create the kubernetes_service_account needed for the rest of my terraform code.

resource "google_container_cluster" "k8s_autopilot_cluster" { ... }

provider kubernetes {
    alias = "k8s_gcloud_temp"
    cluster_ca_certificate  = base64decode(google_container_cluster.k8s_autopilot_cluster.master_auth.0.cluster_ca_certificate)
    host                    = google_container_cluster.k8s_autopilot_cluster.endpoint
    client_certificate      = base64decode(google_container_cluster.k8s_autopilot_cluster.master_auth.0.client_certificate)
    client_key              = base64decode(google_container_cluster.k8s_autopilot_cluster.master_auth.0.client_key)
}

resource "kubernetes_service_account" "terraform_k8s_sa" {
    provider = kubernetes.k8s_gcloud_temp
    metadata {
        namespace = "kube-system"
        name = "terraform-k8s-sa"
    }

  automount_service_account_token = false
}

So my cluster is created successfully, but the creation of my kubernetes_service_account always fails with Error: serviceaccounts is forbidden: User "system:anonymous" cannot create resource "serviceaccounts" in API group "" in the namespace "kube-system".

Any idea why I cannot use master_auth and what I should use instead?


Solution 1:

data "google_client_config" "provider" {}
provider kubernetes {
    alias = "k8s_gcloud_temp"
    cluster_ca_certificate  = base64decode(google_container_cluster.k8s_autopilot_cluster.master_auth.0.cluster_ca_certificate)
    host                    = google_container_cluster.k8s_autopilot_cluster.endpoint
    token = data.google_client_config.provider.access_token
}