This message was deleted.
# discuss-terraform
a
This message was deleted.
b
Yeah, generally you would import an object that already exists rather than expecting TF to adopt the object.
f
ok, thanks. I added some logic through remote exec to deal with that 👍
b
here is a snippet that I have found is useful:
Copy code
resource "kubernetes_namespace" "cattle-system" {
  metadata {
    name = "cattle-system"
  }
  lifecycle {
    ignore_changes = [
      metadata,
    ]
  }
  provisioner "local-exec" {
    command = <<-EOT
    kubectl get namespace "cattle-system" -o json  \
     | tr -d "\n" \
     | sed "s/\"finalizers\": \[[^]]\+\]/\"finalizers\": []/"   \
     | kubectl replace --raw /api/v1/namespaces/cattle-system/finalize -f -
    EOT
    when    = destroy
  }
  provisioner "local-exec" {
    command = <<-EOT
      sleep 15
    EOT
    when    = destroy
  }
}
👍 1
removing finalizers when a namespace is stuck is helpful for destroy
f
i kind of solved it in my Taskfiles having tasks to run before and after deploying that tries to deal with that too
something like:
Copy code
create-ns:
    desc: Create the k8s namespace if it doesn't exist
    deps: [echo-vars]
    requires:
      vars:
        - KUBE_CONTEXT_HARVESTER
        - KUBE_CONTEXT_K8S_CLUSTER
        - ENV
    cmds:
      - |
        if ! kubectl get namespace {{.KUBE_CONTEXT_K8S_CLUSTER}} --context {{.KUBE_CONTEXT_HARVESTER}}; then
          kubectl create namespace {{.KUBE_CONTEXT_K8S_CLUSTER}} --context {{.KUBE_CONTEXT_HARVESTER}}
          echo "Namespace '{{.KUBE_CONTEXT_K8S_CLUSTER}}' created."
        else
          echo "Namespace '{{.KUBE_CONTEXT_K8S_CLUSTER}}' already exists."
        fi

  destroy-ns:
    desc: Delete the k8s namespace if it's empty
    deps: [echo-vars]
    requires:
      vars:
        - KUBE_CONTEXT_HARVESTER
        - KUBE_CONTEXT_K8S_CLUSTER
        - ENV
    cmds:
      - |
        if [[ -z $(kubectl get all --namespace {{.KUBE_CONTEXT_K8S_CLUSTER}} --context {{.KUBE_CONTEXT_HARVESTER}} -o name) ]]; then
          kubectl delete namespace {{.KUBE_CONTEXT_K8S_CLUSTER}} --context {{.KUBE_CONTEXT_HARVESTER}}
          echo "Namespace '{{.KUBE_CONTEXT_K8S_CLUSTER}}' deleted because it was empty."
        else
          echo "Namespace '{{.KUBE_CONTEXT_K8S_CLUSTER}}' is not empty; skipping deletion."
        fi
then have it as dependencies in the tasks to apply and destroy