Terraform import for Kubernetes resources

NIRAV SHAH
2 min readJan 23, 2023

We have all our resources created with terraform. However, we realised few resources like namespace are not part of terraform code. Later we added but its import got a little tricky for me. I am sharing simple steps here.

Problem:

We realised we need to import as resources already existed in the system.

terraform-bin apply -auto-approve -input=false tf.plan
kubernetes_namespace.logging_namespace: Creating...

│ Error: namespaces "logging" already exists

│ with kubernetes_namespace.logging_namespace,
│ on logging.tf line 40, in resource "kubernetes_namespace" "logging_namespace":
│ 40: resource "kubernetes_namespace" "logging_namespace" {

Error while normal import:

terraform import -var-file=tfvars/latest.tfvars kubernetes_namespace.logging_namespace logging
Acquiring state lock. This may take a few moments...
kubernetes_namespace.logging_namespace: Importing from ID "logging"...
kubernetes_namespace.logging_namespace: Import prepared!
Prepared kubernetes_namespace for import
kubernetes_namespace.logging_namespace: Refreshing state... [id=logging]

│ Error: Unauthorized




Releasing state lock. This may take a few moments...

Solution:

As we are doing import locally, the values in kubernetes provider are not resolved & hence it is failing. So we need to change kubernetes configuration as below & point manually to correct cluster:

provider "kubernetes" {
host = data.aws_eks_cluster.cluster.endpoint
cluster_ca_certificate = base64decode(data.aws_eks_cluster.cluster.certificate_authority.0.data)
token = data.aws_eks_cluster_auth.cluster.token
}

to

provider "kubernetes" {
config_path = "~/.kube/config"
}

Run command:

kubectl config use-context latest-eks

terraform import -var-file=tfvars/latest.tfvars kubernetes_namespace.logging_namespace logging
Acquiring state lock. This may take a few moments...
kubernetes_namespace.logging_namespace: Importing from ID "logging"...
kubernetes_namespace.logging_namespace: Import prepared!
Prepared kubernetes_namespace for import
kubernetes_namespace.logging_namespace: Refreshing state... [id=logging]

Import successful!

The resources that were imported are shown above. These resources are now in
your Terraform state and will henceforth be managed by Terraform.

Releasing state lock. This may take a few moments...

Reference

--

--

NIRAV SHAH

Working as Cloud Architect & Software enthusiastic