Search code examples
terraformterraform-provider-azure

Terraform Azure get resource id


I have terraform module to create private endpoint for various type of resources (storageaccount, logic apps, function apps ..etc) While createing privatendpoint I need provide private_connection_resource_id. Is there a way to get the resource_id with data source, based on resource name, I also have the resource group information?

I tried to get it this way

data "azurerm_resources" "resource" {
  name                = var.resource_name
}

I get this error

   on private-endpoint/main.tf line 32, in resource "azurerm_private_endpoint" "privateendpoint":
│   32:     private_connection_resource_id = data.azurerm_resources.resource-id[*].id
│     ├────────────────
│     │ data.azurerm_resources.resource-id is object with 7 attributes
│ 
│ Inappropriate value for attribute "private_connection_resource_id": string
│ required.
╵
╷
│ Error: Incorrect attribute value type

Solution

  • The data "azurerm_resources" block outputs a list of objects, and you need to extract a specific attribute from the result. Try this code below and hope it works.

    data "azurerm_resources" "resource" {
      name = var.resource_name
    }
    
    # Assuming var.resource_name uniquely identifies the resource in a given resource group
    locals {
      resource_id = data.azurerm_resources.resource[*].id[0]
    }
    
    resource "azurerm_private_endpoint" "privateendpoint" {
      # other attributes...
    
      private_connection_resource_id = local.resource_id
    }