User data scripts are long inline strings. How do you manage them?
BeginnerScenarioResources Variables and Expressions
Answer
Situation read → Unreadable heredocs inside HCL.
What I'd do → Move the script into a template file and render it.
resource "aws_instance" "app" {
user_data = templatefile("${path.module}/templates/boot.sh.tftpl", {
app_version = var.app_version
region = var.region
})
user_data_replace_on_change = true
}
Why → The script becomes lintable shell, and user_data_replace_on_change makes the change visible in the plan as a replacement.
Interview tip → Escape literal ${ as $${ in template files.
More on Resources Variables and Expressions
You need three identical web servers. How do you declare them, and what is the catch with `count`?BeginnerYou manage subnets from a list of CIDRs. Someone removes the second CIDR and Terraform plans to recreate the third subnet. Why, and what do you change?IntermediateHow do you stop someone passing `environment = "production"` when only `dev`, `stage` and `prod` are valid?BeginnerA module takes a database password and exposes the connection string as an output. How do you stop them leaking into plan output?BeginnerA monitoring stack should only exist in prod. How do you create a resource conditionally?BeginnerYou have subnets defined as `{ web = {...}, db = {...} }` per VPC, nested two levels deep. How do you create them with `for_each`?Advanced