Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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
}
like image 698
alt-f4 Avatar asked Oct 16 '25 17:10

alt-f4


2 Answers

You can use kubernetes_manifest for that. Quoting from its docs:

Represents one Kubernetes resource by supplying a manifest attribute. The manifest value is the HCL representation of a Kubernetes YAML manifest. To convert an existing manifest from YAML to HCL, you can use the Terraform built-in function yamldecode() or tfk8s.

So, you could do:

resource "kubernetes_manifest" "test" {
  manifest = yamldecode(file("${path.module}/config.yml"))
}
like image 145
Yajo Avatar answered Oct 18 '25 16:10

Yajo


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.

like image 20
Markus Dresch Avatar answered Oct 18 '25 14:10

Markus Dresch



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!