azure - 如何使用 Terraform 将 log-to-eventhub 策略添加到 Azure API 管理策略
问题描述
我想使用 terraform 向 Azure API 管理 API 添加策略
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
}
我可以通过门户创建此策略。我可以使用 terraform 创建 APIM 实例和 API,但是当我尝试创建策略时,我收到以下验证错误:
│ 错误:创建或更新 API Policy ...:apimanagement.APIPolicyClient#CreateOrUpdate:响应请求失败:StatusCode=400 -- 原始错误:autorest/azure:服务返回错误。Status=400 Code="ValidationError" Message="一个或多个字段包含不正确的值:" Details=[{"code":"ValidationError","message":"第 3 行元素 'log-to-eventhub' 中的错误,第 11 列:Log to EventHub 仅接受 azureEventHub" ,"target":"log-to-eventhub"}] 的Logger 类型
谁能建议我如何将策略与创建的事件中心相匹配?
解决方案
您可以使用Set-AzApiManagementPolicy PowerShell 命令为 API 管理设置 API 范围策略。
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
您可以参考Set-AzureRmApiManagementPolicy 中的 GitHub 已关闭问题不显示验证错误和如何更新 API 策略中的未解决问题?.
其他参考:如何在 Azure API 管理中将事件记录到 Azure 事件中心并从 powershell 更新 azure api 入站策略