Aidan
Aidan

Reputation: 4901

How to add a log-to-eventhub policy to an Azure API Management Policy using Terraform

I would like to add a policy to an Azure API Management API using terraform

resource "azurerm_eventhub" "my-event-hub" {
  name                = "my-logger"
  namespace_name      = azurerm_eventhub_namespace.my-events.name
  resource_group_name = azurerm_resource_group.myresourcegroup.name
  partition_count     = 2
  message_retention   = 1
}
resource "azurerm_api_management_api_policy" "eventhub-policy" {
  api_name            = azurerm_api_management_api.my-apim.name
  api_management_name = azurerm_api_management.my-api.name
  resource_group_name = azurerm_resource_group.myresourcegroup.name

  xml_content = <<XML
  <policies>s
    <inbound>
       <log-to-eventhub logger-id="my-logger">@{
         return new JObject(
            #***** json objects here *********#
         ).ToString();
         }</log-to-eventhub>
     <base />
     <set-backend-service base-url="https://my-stub.getsandbox.com" />
   </inbound>
  <backend>
      <base />
  </backend>
  <outbound>
      <base />
  </outbound>
  <on-error>
      <base />
  </on-error>
</policies>
XML
}

I can create this policy through the portal. I can create the APIM instance and the API using terraform, but when I try to create the policy I get the following validation error:

│ Error: creating or updating API Policy ...: apimanagement.APIPolicyClient#CreateOrUpdate: Failure responding to request: StatusCode=400 -- Original Error: autorest/azure: Service returned an error. Status=400 Code="ValidationError" Message="One or more fields contain incorrect values:" Details=[{"code":"ValidationError","message":"Error in element 'log-to-eventhub' on line 3, column 11: Log to EventHub only accepts Logger Type of azureEventHub","target":"log-to-eventhub"}]

Can anyone suggest how I match the policy to the created event hub?

Upvotes: 0

Views: 578

Answers (1)

Ecstasy
Ecstasy

Reputation: 1864

You can use Set-AzApiManagementPolicy PowerShell command to set API-scope policy for API Management.

Set-AzApiManagementPolicy
   -Context <PsApiManagementContext>
   [-Format <String>]
   -ApiId <String>
   [-ApiRevision <String>]
   -OperationId <String>
   [-Policy <String>]
   [-PolicyFilePath <String>]
   [-PolicyUrl <String>]
   [-PassThru]
   [-DefaultProfile <IAzureContextContainer>]
   [<CommonParameters>]

$apimContext = New-AzApiManagementContext -ResourceGroupName "Api-Default-WestUS" -ServiceName "contoso"
Set-AzApiManagementPolicy -Context $apimContext -ApiId "9876543210" -Policy $PolicyString

You can refer to GitHub closed issue at Set-AzureRmApiManagementPolicy does not show validation errors and open issue at How to update API Policy?.

Other references: How to log events to Azure Event Hubs in Azure API Management and Update azure api inbound policy from powershell

Upvotes: 1

Related Questions