How do I deploy a Kubernetes service through YAML using Terraform?

Viewed 962

I am learning Kubernetes, and my objective is to deploy a Kubernetes but using Yaml files through terraform (Kubernetes provider). Let me illustrate with an example:

As per I understand that I can have a ConfigMap as a resource, like:

resource "kubernetes_config_map" "config" {
  metadata {
    namespace = "metallb_system"
    name = "config"
  }
  data {
    config = "${file(${path.module}/config.yml)}"
  }
}

And now I would like to deploy a service, which in HCL looks like:

resource "kubernetes_service" "nginx" {

  metadata {
    name = "nginx-example-bla"
  }
  spec {
    selector = {
      App = kubernetes_pod.airflow.metadata[0].labels.App
    }
    port {
      port        = 80
      target_port = 8080
    }

    type = "LoadBalancer"
  }
}

But I would like to do it with yaml instead of HCL.

So (hypothetically), I want to be able do something like:

resource "kubernetes_service" "nginx" {
  file = kubernetes_config_map.config  # Not sure if ConfigMap is the right usage here but I want to be able to deploy a service through Yaml
}
1 Answers

Terraform only tracks resources added with HCL, using file() only adds contents. So if you want terraform to manage your k8s resources (detect changes or the deletion of those resources), you'll have to stick with that.

If you simply want to deploy your YAML files using terraform instead, you can run commands using a "null_resource":

resource "null_resource" "deploy-yaml" {

  provisioner "local-exec" {
      command = "kubectl apply -f xxx.yaml"
  }
}

If you do this, keep in mind, that terraform does not have any change detection now. So if the YAML changed, terraform does not know about it. You'd have to trigger it by quick and dirty changing the resource name or using some always changing value (for example a random_uuid) to rerun the script.

Related