It is often more straightforward to make Terraform work for the single case, then use the count
parameter to expand it to > 1 cases.
As the docs mention, you cannot access interpolation functions inside of the template, you need to pass them through the variables
resouce in template_dir
.
To access interpolations that are normally available to Terraform configuration (such as other variables, resource attributes, module outputs, etc.) you'll have to expose them via vars [...]
For a single database_user
, we pass the database_user
as into the template_dir
to use as ${user}
sql_templates/create_user.sql
CREATE USER ${user} FOR LOGON ${user};
EXEC sp_addrolemember 'db_datareader','${user}'
GO
main.tf
variable "database_user" {
default = "td"
}
resource "template_dir" "config" {
source_dir = "sql_templates"
destination_dir = "sql_scripts"
vars = {
user = "${var.database_user}"
}
}
This creates the expected output
.
├── main.tf
├── sql_scripts
│ └── create_user.sql
└── sql_templates
└── create_user.sql
To expand this to multiple database_users
, you can make use of count
inside the
template_dir
resource.
main.tf
variable "database_users" {
default = ["td", "tdus", "tdbusrs"]
}
resource "template_dir" "config" {
source_dir = "sql_templates"
destination_dir = "sql_scripts/${var.database_users[count.index]}/"
count = "${length(var.database_users)}"
vars = {
user = "${element(var.database_users, count.index)}"
}
}
Note: The use of ${var.database_users[count.index]}
inside
desination_dir
prevents terraform from using the same destination for all the
rendered outputs, and instead creates a new subfolder for each user
.
├── main.tf
├── sql_scripts
│ ├── td
│ │ └── create_user.sql
│ ├── tdbusrs
│ │ └── create_user.sql
│ └── tdus
│ └── create_user.sql
└── sql_templates
└── create_user.sql