DEV Community

Liptan Biswas
Liptan Biswas

Posted on • Edited on

3

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

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (0)

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay