Terraform has gained immense popularity in terms of managing the infrastructure in the GitOps way.
When spinning up virtual machines in AWS or GCP, we have an option to pass a startup script. The startup script gets executed when the VM starts up. We can use this functionality for various tasks, like installing some software, registering the node somewhere, etc.
Sometimes, we need to dynamically populate some variables in the startup scripts, such as dynamically generate and use some credentials. We can use Terraform's template function to render the script, replacing the variables with their actual value.
Here's how it's done.
Define a variable
variable "my_var" {
type = string
default = "Hello"
}
Rander your startup script
data "template_file" "startup_script" {
template = file("${path.module}/startup.sh")
vars = {
some_var = var.my_var
//you can use any variable directly here
}
}
Example Startup script
#!/bin/bash
export TEST_VARIABLE=${some_var}
Finally, use the rendered template
...
user_data = data.template_file.startup_script.rendered
...
Cheers. The "userdata" will have the actual values of the variables.
Further reading: https://spacelift.io/blog/terraform-templates
Top comments (0)