Add existing GKE cluster to terraform stat file

8/11/2021

Lets assume I have an existing GKE cluster that contains all my applications. They were all deployed using different methods. Now I want to deploy some resources to that cluster using Terraform. The trouble here is that terraform doesn't see it in his state file so it can't interact with it. Another problem is that even if I get that cluster to my state file, terraform doesn't see all of the created resources in that cluster. This could lead to some conflicts e.g. I'm trying to deploy two resources with the same name. Is there a way to solve this problem or do I just have to deal with the reality of my existence and create a new cluster for every new project that I deploy with terraform?

-- SyntioBen
google-kubernetes-engine
hashicorp
kubernetes
terraform

1 Answer

8/11/2021

You can use terraform import command to import your existing GKE cluster to terraform state. Prior to run it, you need to have the adequate terraform configuration for your cluster.

example of import command :

terraform import google_container_cluster.<TF_RESOURCE_NAME> projects/<PROJECT_ID>/locations/<YOUR-CLUSTER-ZONE>/clusters/<CLUSTER_NAME>

for a terraform configuration :

resource "google_container_cluster" "<TF_RESOURCE_NAME>" {
  name     = "<CLUSTER_NAME>"
  location = "<YOUR-CLUSTER-ZONE>"

}

The CLUSTER_NAME is the name displayed in your GKE clusters list on Google Cloud Console.

Then you need also to import the cluster node pool(s) in the same way using terraform google_container_node_pool resource.

-- MBHA Phoenix
Source: StackOverflow