Recently I required an easy way to retrieve the resource id of an Azure resource and share it between configurations when working with Terraform. In my case I needed the resource id of a Log Analytics Workspace to be able to configure diagnostic logging on different Azure resources.
While you can use the traditional data source method to get the resource id it requires you to input the resource name and resource group for each configuration, example below.
data "azurerm_log_analytics_workspace" "example" {
name = "MyLogAnalyticsWorkspace"
resource_group_name = "MyLogAnalyticsWorkspaceResourceGroup"
}
An alternative method is to utilise the terraform_remote_state data source to retrieve the resource id.
When I deployed the Log Analytics Workspace I created an output value containing the Log Analytics Workspace resource id, example below.
output "log_analytics_resource_id" {
value = azurerm_log_analytics_workspace.log_analytics_example.id
}
This will store the Log Analytics Workspace resource id as an output in the remote state which can now be accessed by any configuration, example below.
data "terraform_remote_state" "production" {
backend = "azurerm"
config = {
key = "prod.terraform.tfstate"
container_name = "tfstate"
resource_group_name = "MyStorageAccountResourceGroup"
storage_account_name = "MyStorageAccount"
}
}
data "azurerm_client_config" "current" {}
resource "azurerm_resource_group" "example" {
name = "example-resources"
location = "Australia Southeast"
}
resource "azurerm_key_vault" "example" {
name = "examplekeyvault"
location = azurerm_resource_group.example.location
resource_group_name = azurerm_resource_group.example.name
enabled_for_disk_encryption = true
tenant_id = data.azurerm_client_config.current.tenant_id
soft_delete_retention_days = 7
purge_protection_enabled = false
sku_name = "standard"
access_policy {
tenant_id = data.azurerm_client_config.current.tenant_id
object_id = data.azurerm_client_config.current.object_id
key_permissions = [
"get",
]
secret_permissions = [
"get",
]
storage_permissions = [
"get",
]
}
}
resource "azurerm_monitor_diagnostic_setting" "example" {
name = "example"
target_resource_id = azurerm_key_vault.example.id
log_analytics_workspace_id = data.terraform_remote_state.production.outputs.log_analytics_resource_id
log {
category = "AuditEvent"
enabled = false
retention_policy {
enabled = false
}
}
metric {
category = "AllMetrics"
retention_policy {
enabled = false
}
}
}
metric {
category = "AllMetrics"
retention_policy {
enabled = false
}
}
}