Template_file dynamic vars

Hi @kstephenson,

First I want to apologize that I didn’t notice you were using count.index as part of the variables there. As you found out, in that case it’s typically easiest to write the templatefile expression inline in the resource block since then count.index will be available for you.

Although I think what you did here makes the most sense for the current situation, I wanted to note that there is a way to get a result corresponding with your old data "template_file" block with count set, like this:

locals {
  dba_user_data = [
    for i in range(var.db_server_count) : templatefile(
      "${path.module}/../../../dev/services/${var.db_type}-cluster/templates/${var.db_type}-user-data.tpl",
      # ...
    )
  ]
}

This for expression using the range function achieves a similar result as a data block with count set, allowing you to use i inside the expression (in this case, in the template variables) in the same way as you might use count.index in a resource block.

You can then access this from inside a resource block that also has count set to var.db_server_count, using an expression like local.dba_user_data[count.index].


With that said, your newer problem with the template apparently not being rendered is interesting. I don’t know a reason why Terraform’s handling of that expression would vary depending on the instance type, but there might be something happening in the AWS provider that I’m not familiar with.

In order to make it easier to see what’s happening, it might be better to switch to using user_data instead of user_data_base64 and remote the base64encode call, and then you can hopefully see in the plan what the result of template rendering is. Then you can check whether it matches what you expected. You can always switch it back to using base64 once you’ve got it working if you like, though unless it’s a big object or contains non-text data I would typically suggest using the plain user_data so that plans will be easier to review.