Is there a way to incorporate the for_each block in a Terraform test file? I have multiple resource groups created and need to devise tests for each one.
Although I can write separate test cases for each resource, I’m wondering if there’s a way to utilize the for_each block within the run block or if there are any alternative suggestions to address this situation?
variable resource_group_variables = {
“resource_group_1” = {
resource_group_name = “test1”
resource_group_location = “eastus2”
resource_group_managed_by = “blabla” #(optional) The ID of the resource or application that manages this Resource Group.
resource_group_tags = {
Created_By = “testuser”,
Department = “IT”
}
},
“resource_group_2” = {
resource_group_name = “test2” #(Required) Name of the Resouce Group with which it should be created.
resource_group_location = “westus”
resource_group_managed_by = “blabla”
resource_group_tags = {
Created_By = “testuser”,
Department = “IT”
}
}
}
Hi @anoop.pc, unfortunately I can’t think of anyway to do this purely within Terraform Test files. We have some long term plans to add for_each support to run blocks, but I think you might actually want them as part of the assertions which is something we haven’t thought much about.
You could potentially write a helper module that loads your target resources via a data source. You can then place a for_each within the data source, and write assertions as post conditions against the data source. Each post condition would then assert against the relevant values in the for_each. Then simply executing the helper module in a run block would attempt to load the data sources and as part of that the post conditions would be validated.
It’s not ideal, but the closest thing I can think of in terms of repeatable assertions. You could write out your idea for for_each meta attributes in assertions as an enhancement request within the Terraform repository. This would raise the issue with our product team.