Put variable in Start-up Scripts using Terraform

liptanbiswas

Liptan Biswas

Posted on September 15, 2020

Put variable in Start-up Scripts using Terraform

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"
}
Enter fullscreen mode Exit fullscreen mode

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
  }
}
Enter fullscreen mode Exit fullscreen mode

Example Startup script

#!/bin/bash

export TEST_VARIABLE=${some_var}
Enter fullscreen mode Exit fullscreen mode

Finally, use the rendered template

...
user_data = data.template_file.startup_script.rendered
...
Enter fullscreen mode Exit fullscreen mode

Cheers. The "userdata" will have the actual values of the variables.

Further reading: https://spacelift.io/blog/terraform-templates

💖 💪 🙅 🚩
liptanbiswas
Liptan Biswas

Posted on September 15, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related