I am writing a terraform script with modules.
I have a module that creates azure application insights using for_each
as below:
resource "azurerm_application_insights" "appinsights-apps" {
for_each = var.app_insights_names
name = each.key
location = var.location
resource_group_name = var.app_insights_rg_name
application_type = "web"
disable_ip_masking = true
workspace_id = var.sf_la_workspace_resource_id
}
Now in want the same module to also create a diagnostic setting for every app insights created:
resource "azurerm_monitor_diagnostic_setting" "appinsights-diag-settings" {
depends_on = [azurerm_application_insights.appinsights-apps]
for_each = azurerm_application_insights.appinsights-apps
name = "diag"
target_resource_id = azurerm_application_insights.appinsights-apps[*].id
storage_account_id = data.azurerm_storage_account.logs-storage.id
enabled_log {
category_group = "allLogs"
}
}
The above does not work for me. I need to somehow pass the id's of application insights created earlier to target_resource_id variable. Should I use terraform output for this? If yes how do I reference the output within the same module?
Without getting into the details of how things work in Azure, the easiest solution would be the following:
resource "azurerm_application_insights" "appinsights-apps" {
for_each = var.app_insights_names
name = each.key
location = var.location
resource_group_name = var.app_insights_rg_name
application_type = "web"
disable_ip_masking = true
workspace_id = var.sf_la_workspace_resource_id
}
resource "azurerm_monitor_diagnostic_setting" "appinsights-diag-settings" {
for_each = azurerm_application_insights.appinsights-apps
name = "diag"
target_resource_id = each.value.id
storage_account_id = data.azurerm_storage_account.logs-storage.id
enabled_log {
category_group = "allLogs"
}
}
Since you are using for_each
chaining between resources, the keys are the same as for the azurerm_application_insights
resource, but you also get the attributes from that resource. This is why you can use each.value.id
to access the id
attribute of the resource.