How to use yaml file in Terraform?

Viewed 8029

I have kubernetes configuration in a seperate yaml file. I want to use that yaml file while running terraform can I do it? If yes, then how.

4 Answers

Yes you can, but you have to use 3rd-part kubernetes provider

# Retrieve an access token as the Terraform runner
data "google_client_config" "provider" {}

# Same parameters as kubernetes provider
data "google_container_cluster" "my-cluster" {
  name      = "my-cluster"
  location  = "europe-west4-a"
}

provider "kubectl" {
  load_config_file       = false
  host                   = "https://${google_container_cluster.my-cluster.endpoint}"
  cluster_ca_certificate = "${base64decode(google_container_cluster.my-cluster.master_auth.0.cluster_ca_certificate)}"
  token = data.google_client_config.provider.access_token
}

data "kubectl_filename_list" "manifests" {
    pattern = "./manifests/*.yml"
}

resource "kubectl_manifest" "test" {
    count     = length(data.kubectl_filename_list.manifests.matches)
    yaml_body = file(element(data.kubectl_filename_list.manifests.matches, count.index))
}

Link to provider https://registry.terraform.io/providers/gavinbunney/kubectl/latest/docs

Similar question How To Run kubectl apply commands in terraform

To answer to the original question specifically, which tags contain Azure and AKS, as well as the asker is requesting to use pure kubernetes yaml manifests in terraform - I've used gavinbunney/kubectl:

terraform {
  required_providers {

    kubectl = {
      source  = "gavinbunney/kubectl"
      version = "1.14.0"
    }
  }
}

provider "kubectl" {
  load_config_file = false
  host = azurerm_kubernetes_cluster.REDACTED.kube_config.0.host
  cluster_ca_certificate = base64decode(azurerm_kubernetes_cluster.REDACTED.kube_config.0.cluster_ca_certificate)
  token = yamldecode(azurerm_kubernetes_cluster.REDACTED.kube_config_raw).users[0].user.token
}

More info could be found in the original topic in Github

According to my experience, Terraform supports the Kubernetes provider, but all the things in that provider are separate, such as deployment, pod, service and etc. It does not provide a way to load all the things from a configuration file.

So, to deploy from the configuration file, I recommend you put the kubectl apply -f config_file in the null_resource. And it's also simple to delete all the things that have deployed with multiple mull_resource, you just need to use the Terraform command terraform destroy, it will remove all the resources that deployed through the Terraform file.

Related