terraform - Unable to fetch service account from Kubernetes: serviceaccounts "<name of service account>" not found

2/22/2022

This was working perfectly fine before but for some reason it no longer is, would appreciate if someone can help fix this:

My terraform code as follows, have replaced key info. with "<>" just for sharing publicly here:

Outer main.tf has this:

    module "<name>_service_account" {
  source = "../modules/kubernetes/service-account"
  name   = "<name>-deployer"
}

# Create <name> platform namespace
resource "kubernetes_namespace" "<name>-platform" {
  metadata {
    name = "<name>-platform"
  }
}

The service account main.tf module:

resource "kubernetes_service_account" "serviceaccount" {
  metadata {
    name      = var.name
    namespace = "kube-system"
  }
}


resource "kubernetes_cluster_role_binding" "serviceaccount" {
  metadata {
    name = var.name
  }

  subject {
    kind = "User"
    name = "system:serviceaccount:kube-system:${var.name}"
  }

  role_ref {
    kind      = "ClusterRole"
    name      = "cluster-admin"
    api_group = "rbac.authorization.k8s.io"
  }
}

data "kubernetes_service_account" "serviceaccount" {
  metadata {
    name = var.name
    namespace = "kube-system"
  }
  depends_on = [
    resource.kubernetes_service_account.serviceaccount
  ]
}

data "kubernetes_secret" "serviceaccount" {
  metadata {
    name = data.kubernetes_service_account.serviceaccount.default_secret_name
    namespace = "kube-system"
  }
  binary_data = {
    "token": ""
  }
  depends_on = [
    resource.kubernetes_service_account.serviceaccount
  ]
}

My outputs.tf for the above module:

output "secret_token" {
    sensitive = true
    value = lookup(data.kubernetes_secret.serviceaccount.binary_data, "token")
}

The error that I get in my terraform pipeline:

│ Error: Unable to fetch service account from Kubernetes: serviceaccounts "<name>-deployer" not found
│   with module.<name>_service_account.data.kubernetes_service_account.serviceaccount,
│   on ../modules/kubernetes/service-account/main.tf line 27, in data "kubernetes_service_account" "serviceaccount":
│   27: data "kubernetes_service_account" "serviceaccount" {
-- terraform-ftw
google-cloud-platform
kubernetes
terraform

1 Answer

2/22/2022

Figured it out, this is a new environment/project and I had the terraform refresh stage still in the pipeline hence why it couldnt find the service account, removing that and just letting the plan and apply run first solved it.

-- terraform-ftw
Source: StackOverflow