Up and Running with templates in Terraform

Terraform has a lot of great formatting and templating tools, but one in particular I make heavy use of is the template_filedata source, which in my case, makes it super simple to pass in variable data from my cloud provider resources (and other resources generated locally when I run Terraform, and then managed in my remote state store) to these templates and use them, in my example, with cloud-init when asking my provider to create a compute resource.

So, let's start with a simple use case where this is useful. My use cases is in provisioning a Kubernetes cluster, so for my cluster nodes, the cloud-init script (in my example, just a bash script, but this can be used for any text resource) needs the cluster controller IP address that API server is running on, the Kubernetes version being used, and the cluster token.

My script is pretty simple in this regard, and the template is saved as node.tpl:

and you'll see for user_data (the DigitalOcean provider idiom for cloud-init), we're referencing data.template_file.node.rendered, which will contain the rendered version of our template above, but in order to render this, we need to, first, create the resource, and then populate those values, local to that resource:

So, you'll see I set my vars to a variety of different sources, some are referencing attributes from another resource (my k8s_primary node's primary_ipv4_address, for example, and a user variable kubernetes_version, and then a random string generated elsewhere in my project).

Then, when you proceed to apply Terraform, the user_data field will be populated by the rendered template, with the data you provided substituted in for the relevant variables.