Search code examples
kubernetesterraformterraform-template-file

Can you define Kubernetes Services / Pods using YAML in Terraform?


I am using the Kubernetes Provider to describe services/pods in Terraform.

It can get confusing using the Hashicorp Configuration Language to define kubernetes_pod or kubernetes_service resources because the Kubernetes documentation describes everything in YAML which it means you need to translate it into HCL.

Is it possible to define pods as YAML and use them with kubernetes_pod and kubernetes_service resources as templates?


Solution

  • While Terraform normally uses HCL, this is a superset of JSON (much like YAML itself) so can also read JSON.

    One possible option would be to take the YAML examples you already have and convert them into JSON and then use Terraform on those.

    Unfortunately, that's unlikely to work because keywords are likely to be different for how Terraform is expecting things so you'd need to write something to do some basic translation of the input YAML to a Terraform resource JSON. At this point, it'd probably be worth just adding HCL output to the conversion so your outputted Terraform config is more readable if you ever intend to keep the Terraform config around instead of just one shot converting and applying the config.

    The benefit of doing things this way would be that you have a reusable Kubernetes config that could be ran using kubectl or other tools but gives you the power of Terraform's lifecycle management, being able to plan changes and integration with non Kubernetes parts of your infrastructure (such as setting up instances to run the Kubernetes cluster on).

    I've not used it much but I believe Kops will allow you to keep pod/service config in typical Kubernetes YAML files but can then use Terraform to manage the configuration and even allows you to output the Terraform configuration so you can run it outside of Kops itself.