DEV Community 👩‍💻👨‍💻

Liptan Biswas
Liptan Biswas

Posted on • Updated on

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}/")
  vars = {
    some_var = var.my_var 
    //you can use any variable directly here
Enter fullscreen mode Exit fullscreen mode

Example Startup script


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:

Top comments (0)

DEV runs on 100% open source code known as Forem.

Contribute to the codebase or host your own.
Check these out! 👇